- Home /
How do I create / Instatiate an array of GameObjects in C#
I'm trying to create an array of "selectors" which will be used in a 3D menu. However, the following code is not working as I expected:
public int numSelectors = 5;
public GameObject[] selectorArr;
public Transform selector; //selected in the editor
// Use this for initialization
void Start () {
selectorArr = new GameObject[numSelectors];
for (int i = 0; i < numSelectors; i++){
selectorArr[i] = (GameObject)Instantiate(selector, new Vector3((float)i,1,0), Quaternion.Euler(new Vector3(0,0,0))) as GameObject;
selectorArr[i].transform.localScale = new Vector3(1,1,1); //This is where the exception occurs.
}
}
When I run this code, I get the following error at the localScale line:
InvalidCastException: Cannot Cast from source type to destination type.
I can't determine why an array of GameObjects would not be able to be edited as GameObjects. Thoughts?
Answer by ScroodgeM · Jul 30, 2012 at 06:05 AM
pay more attention to code. exception should be raised one line higher.
Instantiate returns type of object that was given to it input.
You give to this method a Transform and try to cast returned object to GameObject.
so, give to input GameObject too or cast it to Transform on output.
using UnityEngine; using System.Collections; public class TestCodeCS : MonoBehaviour { public int numSelectors = 5; public GameObject[] selectorArr; public GameObject selector; //selected in the editor void Start() { selectorArr = new GameObject[numSelectors]; for (int i = 0; i < numSelectors; i++) { GameObject go = Instantiate(selector, new Vector3((float)i, 1, 0), Quaternion.identity) as GameObject; go.transform.localScale = Vector3.one; selectorArr[i] = go; } } }
Thank you for your feedback. The tutorial that I was following used the "Transform" type, and it seemed to work for instantiation. I also find it odd that the Array was allowing me to put non-GameObjects in it when it was initialized as an array of GameObjects. For instance, in my code above, if I comment out the selectorArr[i].Transform...
line, it runs properly (which is why I assumed that is where the exception occurred).
this line is not one i needn't 8) this way lets me to call array just once ins$$anonymous$$d of twice 8) little more performance 8)
Answer by mcroswell · Dec 27, 2012 at 09:21 PM
Your code was fine except for the double-cast. Either use "(GameObject)" or "as GameObject", not both. Let me know. Just browsing here.