Reputation: 183
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
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
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
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