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?
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 .
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.
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
Something like this?
Component[] components = GetComponents(typeof(Component));
for(int i = 0; i < components.Length; i++)
{
Debug.Log(components[i].name);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With