How to get array of child objects contained in a GameObject

1.5k Views Asked by At

I have a GameObject in Unity that is supposed to serve as a container for some definitions.

object explorer

I'd like to access that object and retrieve the Def class instances (every object there is instance of Def general class).

So, if I have a GameObject instance, how can I retrieve all objects that are instances of specific class?

3

There are 3 best solutions below

0
On BEST ANSWER

You can use the GameObject.GetComponents<Def>(); to retrieve all components of Def type in the GameObject.
More info in the Unity Docs http://docs.unity3d.com/ScriptReference/GameObject.GetComponents.html

0
On

As long as you have a GameObject reference you can use GetComponents().

Def [] list = gameObject.GetComponents<Def>();
0
On
public Def[] defArray;
public Defs gameobject; ///if you want to access from another class assign this your Defs gameobject from inspector

defs = Defs.GetComponents<Def>();  ///if you want access from another game object
defs = gameObject.GetComponents<Def>();  ///if Defs is attached to this gameObject