Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of all of components of a game object in Unity

Tags:

c#

unity3d

Say, I have a game object in my scene which has 12 components. Some of these components might be of the same type: for example, this game object might have two audio sources. Now, I want to add a C# script to this game object in a way that it collects the name of all of these components (in a list?), and prints them out in the console. How can I do that?

like image 432
Gordafarid Avatar asked Mar 23 '18 12:03

Gordafarid


People also ask

How do I get GameObject components?

GameObjects are not Components and cannot be retrieved with GetComponent(). You can assign it in the inspector because then the inspector knows to look for a GameObject. If you want the GameObject that your script is attached to, then just use this. gameObject .

What are the components of GameObject Unity?

Specifically, a Camera Component, a GUILayer, a Flare Layer, and an Audio Listener. All of these components provide functionality to this GameObject. Rigidbody, Collider, Particle System, and Audio are all different components that you can add to a GameObject.


2 Answers

Use GetComponents method to get array of components, as shown below.

Component[] components = gameObject.GetComponents(typeof(Component));
foreach(Component component in components) {
    Debug.Log(component.ToString());
}

This will also display the duplicate components added to the GameObject

like image 112
Patt Mehta Avatar answered Oct 12 '22 23:10

Patt Mehta


Something like this?

    Component[] components = GetComponents(typeof(Component));
    for(int i = 0; i < components.Length; i++)
    {
        Debug.Log(components[i].name);
    }
like image 21
Ryanas Avatar answered Oct 12 '22 22:10

Ryanas