- Home /
Instantiating many objects
Hi,
I am attempting to create a procedural sort of map built out of many cubes. I've created a cube prefab and using the following code to instantiate inside a double loop:
UnityEngine.GameObject o = (UnityEngine.GameObject)UnityEngine.GameObject.Instantiate (r, new Vector3 ((float)i, map[i,j] * 1.5F, (float)j), Quaternion.identity);
o.transform.parent = mapRoot.transform;
Creating such a 50X50 map takes a long time. I've profiled and it takes 5-6 ms to create the object and 5-6 ms to set the transform. Does that make sense? It makes the map load extremely slow, and this is not even close to the map size I want to have.
Why are you instantiating the cubes at runtime? Why not just build the map manually, tag them all the same, then if you need access to them later you can put them all into an array?
delay a few spots between the generation, and make a loading bar, as it progresses through a few stages of the generation, have the loading bar...load. Not much help I know, but atleast you can kill that feeling of oh god this takes forever is it working lol
also, do any calculations you can before the instantiation starts, like if your doign that whatever * 1.5f calculation, is there a good reason you cant deter$$anonymous$$e those numbers beforehand and just plug em in as a variable at instantiation time? maybe that would speed things up...
Answer by Vonni · May 25, 2013 at 05:38 PM
50x50 cubes should not take long to instantiate. It should be ~instant.
Btw, when you call o.transform.parent = mapRoot.transform, you are actually calling two GetComponent(Transform)'s and those are somewhat heavy operations.
So what you should do is:
Store all the instantiated objects as Transform instead of GameObject.
Store the mapRoot as a Transform, so you dont have to mapRoot.GetComponent(Transform).