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.

To answer with a code example, try this:

var objects = GameObject.FindGameObjectsWithTag("ObjectTagName");
for (var i : int = 0; i < objects.length; i++)
{
     objects*.GetComponent(nameOfComponent).DoSomething();*

}

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?

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 :slight_smile:

    // and loop somewhere
    for (int i = 0; i < myListOfTypes.Count; i++)
    {
         myListOfTypes*.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.