Just starting out with my first two scenes, a MainMenu and Level1 and I’m having some issues understanding how to get things to load before I start my scene.
Level1’s Start method instantiates a bunch of cube prefabs to create a 60 x 60 grid. This is causing 3 seconds of lag when I start the Level1 scene (understandably), where nothing responds. So it feels like there should be a way to get the instantiation work to happen before I call Application.LoadLevel(“Level1”) from my MainMenu, so that when you arrive at this scene everything is loaded.
But my grid is part of my Level1 scene, so I need to arrive at the Level1 scene first before I instantiate things right?
Confused, any advice/links appreciated.
The code in my Start method in Level1 is:
void Start()
{
//...
// Cover our BaseRock with blocks (cubes) of earth.
for (var x = startingBaseRockXEdgeStart; x < startingBaseRockXEdgeEnd; x++)
{
for (var z = startingBaseRockZEdgeStart; z < startingBaseRockZEdgeEnd; z++)
{
Instantiate(cubePrefab, new Vector3(x*cubePrefabXScale, 5, z*cubePrefabZScale), Quaternion.identity);
}
}
//...
}
I don’t think it’s possible to create instances in a scene without opening it. What you need to do is make a loading screen that appears when Level1 starts but covers up Level1 until its ready to be viewed, (most games do this I believe if they have things they need to do before the Level is ready).
If you create all the instances in one call, it will block everything. So, generating before LoadLevel is not going to solve your problem. Since there is no real multithreading available under Unity, you will need to split the generation up into several calls. You can do this by pulling the x/z counters up into class fields and use them over time.
Here is a quick example (C#):
// keep track of the current state
enum State
{
New,
Generating,
Ready
};
State state = State.New;
void Update()
{
// Before doing anything, make sure, everything is initialized
if(state != State.Ready)
{
Init();
return;
}
// ...
}
//..
int currentGeneratingX;
void Init()
{
//...
switch(state)
{
case State.New:
currentGeneratingX = startingBaseRockXEdgeStart;
state = State.Generating;
break;
case State.Generating:
// Cover our BaseRock with blocks (cubes) of earth. One X at a time.
if(currentGeneratingX < startingBaseRockXEdgeEnd)
{
for (var z = startingBaseRockZEdgeStart; z < startingBaseRockZEdgeEnd; z++)
{
Instantiate(cubePrefab, new Vector3(currentGeneratingX*cubePrefabXScale, 5, z*cubePrefabZScale), Quaternion.identity);
}
// increase X for the next set of blocks
currentGeneratingX++;
}
else state = State.Ready;
}
//...
}