For instance:
public class CubeLayout : MonoBehaviour {
public Transform cube;
// Use this for initialization
void Start () {
GameObject obj;
for (float i=0f; i<1000f; i+=100f) {
for (float j=0f; j<1000f; j+=100f) {
obj = (GameObject)Instantiate(cube, new Vector3(i-500f + 40f + 10f, 1.0f, j-500f + 40f + 10f), cube.rotation);
}
}
}
// Update is called once per frame
void Update () {
}
}
This only created ONE instance of a Cube prefab. Now, here is the strange thing: if I remove the “GameObject” variable and just execute the loop this way, it works! Like this:
public class CubeLayout : MonoBehaviour {
public Transform cube;
// Use this for initialization
void Start () {
for (float i=0f; i<1000f; i+=100f) {
for (float j=0f; j<1000f; j+=100f) {
Instantiate(cube, new Vector3(i-500f + 40f + 10f, 1.0f, j-500f + 40f + 10f), cube.rotation);
}
}
}
// Update is called once per frame
void Update () {
}
}
I have no idea why this would be!!
What really happened was it did the first Instantiate, then the error crashed the loop, spawning only one. If you looked, you would have seen the InvalidCastException error at the bottom.
Instantiate really returns a transform so changing obj’s type would work:
Transform obj = Instantiate(...);
^^^^^^^^^
The reason to “catch” an Instantiate is to hand-modify it afterwards, and Transforms are what you usually want for that. If you really need a gameObject, you get to use:
GameObject obj = Instantiate(....) as GameObject;
^^^^^^^^^^^^^
Your obj variable is declared INSIDE the start function. So each new obj you create overrides its value and therefore removes the previously created reference. Even in your first code example all prefabs should have been instantiated, you probably only don’t realize it because of the corrupted reference value.
Move “GameObject obj;” outside the start function and declare it as an array.
You should declare the variables inside the loop:
using UnityEngine;
public class Test : MonoBehaviour {
public GameObject cube;
void Start() {
for (int i=0; i < 3; i++) {
for (int j=0; j < 3; j++) {
GameObject obj = (GameObject)Instantiate(cube);
obj.name = i.ToString() + j.ToString();
}
}
}
}
By the way, always post complete working code, so people don’t have to guess at the stuff you left out (which might be the problem).
I think I figured out the problem. I was trying to cast to GameObject when the cast has to be to type Object. See here:
link text
Just not sure why so many examples I see show different types.