- Home /
Variables on Instantiated Object Cannot Be Changed
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?
Have you tried FindObjectsOfType ins$$anonymous$$d of FindGameObjectsWithTag ?
Answer by MichaI · Dec 21, 2019 at 10:32 PM
Try:
EnemyAI[] enemies = GameObject.FindObjectsOfType<EnemyAI>();
foreach (EnemyAI enemy in enemies)
{
enemy.InvisibleOn();
}
That did it, thanks much! Out of curiosity, what is the difference between "FindObjectsOfType" and finding objects and getting the components?
To be honest I don't know why it didn't work in your case. I think that you could misspelled the tag or you tagged the wrong game object. This way is much more efficient and its less likely to make some mistake.
Another possibility is that multiple scripts were on the same objects.
Your answer
Follow this Question
Related Questions
comparing variables of gameobjects in an array 2 Answers
GameObject[0].SetActive (false); more than one GamObject possible? 2 Answers
cant set object in prefab object, but can in the scene 1 Answer
same script on multiple objects access to different variables from another script 0 Answers
How does WaitForSeconds pass values? 0 Answers