For loop and instantiate problems,void Start() running multiple times
I have a script that looks like this: void grid() { for (int x = 0; x < gridLength; x++) { for (int y = 0; y < gridHeight; y++) { Debug.Log(x + ", " + y); Instantiate(prefab, new Vector3(x - gridLength/2, y - gridHeight/2, 0), Quaternion.identity); } } } private void Start() { grid(); Destroy(gameObject); }
Which does draw a grid but outputs the following several million times:0, 0 InvalidCastException: Specified cast is not valid. (wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
,`void grid() { for (int x = 0; x < gridLength; x++) { for (int y = 0; y < gridHeight; y++) { Debug.Log(x + ", " + y); Instantiate(prefab, new Vector3(x - gridLength/2, y - gridHeight/2, 0), Quaternion.identity); } } } private void Start() { grid(); Destroy(gameObject); }` Firstly, this loop runs forever somehow. Secondly, the output window contains0, 0 InvalidCastException: Specified cast is not valid. (wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
a million times
Hi, couldn't reproduce your issue with the code provided and an empty Unity project, so the issue might be somewhere else, not in the script you provided (I used Unity 2020.3.22f1 and assumed that gridLength and gridHeight are int type variables). Console error should also provide a bit more info about what's happening if you click on it (eg. which file and exact line the issue occurs).