- Home /
Accesing components on multiple objects in scene
Hi,
So I instantiated multiple object with all the same attached script component (let's call it MyScript.js).
And I want to access all those objects from another objects script component (let's call this one Control.js).
So is there a way in Unity to access all of those in once?
I tried something similar to this:
for (var i : int = 0; i < NumberOfObjects; i++) {
GameObject.FindWithTag("ObjectTagName").GetComponent(MyScript).DoSomething();
}
But that did't worked out for me. But if I leave the code outside of the for loop, it works for just one Object in the scene.
Answer by Taugeshtu · Jun 25, 2011 at 02:56 PM
That's what you're trying to do:
Run loop with no imaginable limit;
Find first gameObject with tag;
Access it's component.
That's WRONG logic. What you should to do:
Run loop for all FindGameObjectsWithTag;
Access gameObject in found array at index;
Access it's component
All you need is located in Scripting Reference in GameObject description. Function is called "FindGameObjectsWithTag" or someth. like this.
PS.
By the way - is it that hard, to scroll manual a bit more down?
Oh yes I see what I'm doing wrong. Thanks, I didn't know about "FindGameObjectsWithTag". But it returns all the gameobjects you're looking for in an array, so I can use this array in a for-loop and access the component on every single gameobject in the array =)
Answer by ckfinite · Jun 25, 2011 at 03:07 PM
To answer with a code example, try this:
var objects = GameObject.FindGameObjectsWithTag("ObjectTagName");
for (var i : int = 0; i < objects.length; i++)
{
objects[i].GetComponent(nameOfComponent).DoSomething();
}
Answer by pavlito · Dec 14, 2015 at 03:53 PM
What I would do is add the objects to a collection as soon as they are instantiated. Then you can easily loop through the collection. You can make the collection add items of your script type, because then you don't need to GetComponent. You can cast it immediately upon instantiate...
MyType newObj = (MyType)Instantiate(prefab);
myListOfTypes.Add(newObj);
... provided that the prefab has the component attached, ofcourse :)
// and loop somewhere
for (int i = 0; i < myListOfTypes.Count; i++)
{
myListOfTypes[i].DoSomething();
}
Depending on when and where you do FindGameObjectsWithTag(), it can have an impact on your performance. If however, you cannot use permanent collections (due to memory restrictions) then, by all means use FindGameObjectsWithTag once, map to array and loop through that.
Your answer
Follow this Question
Related Questions
[SOLVED] Save System with Serialize multiple objects 2 Answers
How to change the color of all objects that use the same material? 0 Answers
Instantiate an array of prefabs? 0 Answers
Is this accurate? Scenes are composed of objects are composed of components are composed of assets 1 Answer
Lag on Collision from Projectile 1 Answer