- Home /
Can't instantiate in loop - crashes unity
I'm trying to loop through an array of times, and plot those times by instantiating gameObjects as points in the environment, making the coordinates of the spawn the same as the times. So far I can't even instantiate ten objects in a for loop, let alone reference the points as array indexes. Here is the code that's crashing the Unity Engine:
using UnityEngine;
using System.Collections;
public class plotGraph : MonoBehaviour {
public GameObject cube;
void Start () {
for(int i=0; i <10; i++){
GameObject newCube = Instantiate(cube, new Vector3(i, i, i), Quaternion.
identity) as GameObject;
}
}
Here is my working solution
public class plotGraph : $$anonymous$$onoBehaviour { public GameObject point; private int[] times = {0,1,4,4,4,5,6,10,7,8}; private float xLocalScale=0.2f; void Start() { int arrLen = times.Length; for(int i=1; i <arrLen; i++){ GameObject point = GameObject.CreatePrimitive(PrimitiveType.Sphere); point.transform.localScale = new Vector3(0.2f,0.2f,0.2f); point.transform.position = new Vector3(i, times[i], 0); if(times[i-1]-times[i] < -2){ point.renderer.material.color = new Color(10,0,0,10); // } } } }
Answer by Americus · Jun 19, 2014 at 12:28 PM
I'd move it to update or an inum, first of all. But I've had the same problem with for statements, to be honest. I'm going to keep watching for possible reasons why this never works, but one solution is to simply write out what the for statement is doing manually, for example (pseudo c#):
private int cap = 10;
private int i = 0;
if (i < 10)
{
Instantiate...
i++;
}