- Home /
Accessing a game object from a script?
Suppose I have an enemy prefab and several isntances of this prefab exist throughout the game world. Now I want to write a script which gets the position of all the enemy prefab instances and does something to them when the player presses the space key (like change their position, damage their health, stuff like that).
How do I go about doing this?
Answer by aldonaletto · Sep 24, 2011 at 02:39 PM
You can use a common tag for all enemies, and get them in an array with FindGameObjectsWithTag:
// Find all game objects with tag Enemy var gos : GameObject[]; gos = GameObject.FindGameObjectsWithTag("Enemy"); // Iterate through them and do whatever you want for (var go: GameObject in gos){ go.transform.position.y += 2; // make all enemies jump 2m! }
yep that works, just out of curiosity is there a way to search for them by name ins$$anonymous$$d of tag or do I need to search by tag then look up names on specific game objects?
GameObject.Find searches by name, but only returns the first object found. It's the best alternative to find some specific object by name, but it's too slow to be used often.