I have an enemy AI script that I attach to all my enemy prefabs. In the script, I have a function that can be called to stop the AI from moving towards the player. The function simply changes a couple variables on the script instance. Here is the function:
public void InvisibleOn ()
{
this.hasTarget = false;
this.search = true;
}
I have a consumable item that, when consumed, runs through all the game objects in the scene with the tag “Enemy”. It then adds them to a list and iterates through the list, calling the “InvisibleOn” function on all the instances. Here is that code (from the “Consumables” script):
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach (GameObject enemy in enemies)
{
enemy.GetComponent<EnemyAI>().InvisibleOn();
}
The issue is that these variables that are changed in the “InvisibleOn” function don’t change for any of the instances except one specific one. For example, say I have bandit01(clone), skeleton01(clone), and bandit02(clone) instances in the game. Only the variables on the bandit01(clone) will be changed. The other two instances do not have their variables changed.
I have made the foreach loop Debug.Log all the names of the game objects it adds to the list, and it correctly adds all the instances. I have also made the “InvisibleOn” function Debug.Log the name of the game object it is attached to when it is called. I see all the instances calling that function, yet for some reason only the aforementioned instance actually has its variables changed.
Is there something that I’m missing here?
MichaI
2
Try:
EnemyAI[] enemies = GameObject.FindObjectsOfType<EnemyAI>();
foreach (EnemyAI enemy in enemies)
{
enemy.InvisibleOn();
}