Gordafarid
Gordafarid

Reputation: 183

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

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?

Upvotes: 12

Views: 37349

Answers (3)

Ryanas
Ryanas

Reputation: 1827

Something like this?

    Component[] components = GetComponents(typeof(Component));
    for(int i = 0; i < components.Length; i++)
    {
        Debug.Log(components[i].name);
    }

Upvotes: 10

Josh Graham
Josh Graham

Reputation: 153

    string text = string.Empty;
    foreach(var component in myGameObject.GetComponents(typeof(Component)))
    {
        text += component.GetType().ToString() + " ";
    }

Example output: "text": "UnityEngine.RectTransform UnityEngine.CanvasRenderer UnityEngine.UI.RawImage UnityEngine.UI.Button DebugLayoverButton UnityEngine.Canvas UnityEngine.UI.GraphicRaycaster UnityEngine.UI.LayoutElement "

Upvotes: 2

Patt Mehta
Patt Mehta

Reputation: 4204

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

Upvotes: 22

Related Questions