- Home /
How to get script components in multiple gameobjects C#
I want to change a variable in a script which is in multiple gameobjects, I tried to use public GameObject enemy; and in the update I had enemy = GameObject.FindGameObjectsWithTag("Enemy"); but that won't work, how do I select every gameobject with tag "Enemy" and change a variable in all of their scripts?
Answer by · Sep 26, 2010 at 07:24 AM
You're on the right track.
You should probably do it less often than in every Update(), but FindGameObjectsWithTag will work. You then need to get the component (script) that the variable is in, using GetComponent, and then you can set it.
- Gather array of all GameObjects tagged as "Enemy"
- Use a forloop to iterate through all those gameObjects, and use GetComponent (or use Messages) to access the variable inside that script.
You just need to make sure that the variable you're declaring on those objects is publicly accessible (i.e. not in a function, and declared as public)
Answer by PeterDC · Sep 26, 2010 at 06:58 AM
Instead of using public
use static
; that should keep your variable the same value in all instances of the script.
That won't work. Using static will make a single, game-wide variable. He's asking to change a variable in multiple GameObjects. Unless he actually needs them all to be the same value, he'll need a public variable in each.
that was actually what I wanted... I wanted to change the health of all of the enemies. thanks for the help.
Your answer
Follow this Question
Related Questions
Why does one script not work on multiple gameobjects? 3 Answers
Games on My Own Website 1 Answer
play music on key press 1 Answer
How to save a multpile choice? 1 Answer