How to spawn mobs or objects safely

Modified on Mon, 15 Jul 2019 at 02:04 PM

When spawning a mob (or object) it's important to ensure the chunk under the mob is generated and rendered. Please note that if the chunk is generated but it's not rendered, the chunk collider nor the NavMesh won't be available therefore the mob could fall below the terrain.


The following code ensures the chunk is ready (collider and NavMesh is generated) before spawning a gameobject:


VoxelPlayEnvironment env = VoxelPlayEnvironment.instance;
if (!env.initialized)
return;
Vector3 position = new Vector3 (Random.value * 50 - 25, 51f, 70);
StartCoroutine(Spawn(position));
...
IEnumerator Spawn(Vector3 position) {
    VoxelChunk chunk = null;
    while (chunk == null || !env.ChunkHasNavMeshReady (chunk)) {
         env.GetChunk (position, out chunk, true);
         yield return null;
    }
     // now it's safe to create the gameobject at position
    ...
}


If you're not using AI (NavMesh) and just want to check the chunk's collider is generated you can simply replace env.ChunkHasNavMeshRead(chunk) in the code above by chunk.isRendered.



Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article