x


How to reach multiple GameObjects' value , enemy AI

Hello everyone, I need help for my AI script. I have my enemy AI script almost ready. My enemies have "playerDetected" value. If this value is true they start shooting. So I want this value to be true when player shoots. I did :

function Shoot(){
var target = GameObject.FindWithTag("Enemy");
var scr = target.GetComponent(EnemyAI);
scr.playerDetected=true;
}

this script works perfect only if there is one enemy in the scene. When I put 2 or more enemies to the scene, only one of them starts shooting. Basically what I want to do is, when I shoot all the objects tagged "Enemy" will change their playerDetected value to true in their scripts. Any ideas ? Thanks :).

more ▼

asked Mar 11 '12 at 10:06 PM

Inan Evin gravatar image

Inan Evin
166 37 58 64

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

FindWithTag only returns the first enemy found in the game objects tree. If you want to warn all enemies, use FindGameObjectsWithTag: this function returns an array with all enemies, and you can set them all

function Shoot(){
var targets: GameObject[] = GameObject.FindGameObjectsWithTag("Enemy");
  for (var target in targets){ // warn all enemies in targets[]
    var scr = target.GetComponent(EnemyAI);
    if (scr) scr.playerDetected=true; // if target has the script, set playerDetect
  }
}
more ▼

answered Mar 12 '12 at 12:40 AM

aldonaletto gravatar image

aldonaletto
41.5k 16 42 197

well that works perfect for javascript, but I also try to do it on C# and I couldn't fit it in C#, mind if you can help me out :) ?

Mar 13 '12 at 07:40 PM Inan Evin

In C#, the function would become something like this (I hope!):

void Shoot(){
  GameObject[] targets = GameObject.FindGameObjectsWithTag("Enemy");
  foreach (GameObject target in targets){ // warn all enemies in targets[]
    EnemyAI scr = target.GetComponent<EnemyAI>();
    if (scr) scr.playerDetected=true; // if target has the script, set playerDetect
  }
}

I usually write in JS (it's much easier), thus the code above may still contain some C# error - let me know if the cranky C# compiler complains about something.

Mar 13 '12 at 08:34 PM aldonaletto

well actually foreach was the thing which i didn't know, so It works :) . You helped me a lot, thanks :).

Mar 13 '12 at 08:56 PM Inan Evin
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x960
x654
x329
x293
x74

asked: Mar 11 '12 at 10:06 PM

Seen: 721 times

Last Updated: Mar 13 '12 at 08:56 PM