- Home /
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 :).
Answer by aldonaletto · Mar 12, 2012 at 12:40 AM
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
}
}
well that works perfect for javascript, but I also try to do it on C# and I couldn't fit it in C#, $$anonymous$$d if you can help me out :) ?
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.
well actually foreach was the thing which i didn't know, so It works :) . You helped me a lot, thanks :).
Your answer
Follow this Question
Related Questions
Make enemy more intelligent 0 Answers
how to make an enemy Ai blow up when you shoot it? 2 Answers
enemy shoot AI precision 1 Answer