I was wondering if it is possible to obtain all the components that a game object has and output their names. I’m asking because I have an ImageTarget (Vuforia SDK) and it is being created Dynamically so I want to know which components are already part of the gameobject and which I will want to dynamically add.
Why not just use GetComponents()?
var allComponents : Component[];
allComponents = gameObject.GetComponents (Component);
for (var component : Component in allComponents) {
Debug.Log(component.name);
}
Note this will include the Transform, too. To also get the Components of all children, use GetComponentsInChildren()
EDIT: Umh, wait…components don’t have names, the loop will just print the GameObject’s name over and over again. What exactly do you mean? Do you want to check their types, to see whether you need to add a particular type?
EDIT2: Example how to figure out which components are not attached yet, and attach them.
var allComponents : Component[];
allComponents = gameObject.GetComponents (Component);
// example: check for MeshRenderer and Material, replace/extend with the components you need
var foundMeshRenderer:bool=false;
var foundScriptOfType_MyScriptType:bool=false;
for (var component : Component in allComponents) {
if(component.GetType()==MeshRenderer)
foundMeshRenderer=true;
else if(component.GetType()==MyScriptType) // use an existing script's name here
foundScriptOfType_MyScriptType=true;
}
if(!foundMeshRenderer)
gameObject.AddComponent(MeshRenderer);
if(!foundScriptOfType_MyScriptType)
gameObject.AddComponent(MyScriptType);
There are more efficient and better ways (for example, using a List<> and/or array.Contains(), but I don’t know the exact syntax for UnityScript, since we program in C# exclusively.
For some reason, when I put in component.GetType rather than component.name it gave me the names of my components:
var allComponents : Component[];
allComponents = gameObject.GetComponents (Component);
for (var component : Component in allComponents) {
Debug.Log(component.GetType());
}