- Home /
C# Function Transform to Gameobject Convert
I'm trying to change a function that uses a transform array into a function that uses a gameobject array. So I can modify the Gameobjects directly since transformArray.gameobject is read only. Except I'm not sure how to keep the functionality intact since the code will only accept a transform variable. Any idea if I can change this?
Original code
void FindGameObjectsChildrenByTag(string tag, ref Transform[] transformArray){
GameObject go = GameObject.FindGameObjectWithTag(tag);
if (go != null){
transformArray = go.GetComponentsInChildren<Transform>();
}
else if (Debug.isDebugBuild)
Debug.LogError(string.Format("No GameObject with tag {0} was found.", tag));
}
Modified Code
void FindGameObjectsChildrenByTag(string tag, ref Gameobject[] gameobjectArray){
GameObject go = GameObject.FindGameObjectWithTag(tag);
if (go != null){
gameobjectArray = go.GetComponentsInChildren<GameObject>();
}
else if (Debug.isDebugBuild)
Debug.LogError(string.Format("No GameObject with tag {0} was found.", tag));
}
Answer by robertbu · May 23, 2014 at 05:49 AM
A GameObject is not a component. The easiest solution is to go back to your original code. Then if you need to access to the game object, just use:
transformArray[i].gameObject
You could first get a Transform array, and then build a GameObject array:
void FindGameObjectsChildrenByTag(string tag, ref Gameobject[] gameobjectArray){
GameObject go = GameObject.FindGameObjectWithTag(tag);
if (go != null){
Transform[] transformAraray = go.GetComponentsInChildren<Transform>();
}
else if (Debug.isDebugBuild)
Debug.LogError(string.Format("No GameObject with tag {0} was found.", tag));
gameobjectArray = new GameObject[transformArray.Length];
for (int i = 0; i < transformArray.Length; i++)
gameobjectArray[i] = transformArray[i].gameObject;
}
Or if you want to do it with simpler code, take a look at LinQ:
Your answer
Follow this Question
Related Questions
C# GameObjectList not Setting Parent 0 Answers
C# Rotate GameObjects Regardless of List Size 2 Answers
C# Change Script Help 1 Answer
C# SetActive GameObject Array 2 Answers
C# GameObject Reverses Z Rotation 0 Answers