Knowing When a MeshCollider is Done Updating

Hi everyone.

I’m having a little issue that I can’t quite figure out how to resolve. I have objects that procedurally generate mesh colliders. These are chunks in a voxel engine. So pieces of the ground basically generate mesh colliders.

What I’m trying to do is write some code that allows the player to be spawned right on top of the ground upon loading the world, rather than falling from the sky from above.

The problem is I don’t know what kind of ground will be there. It could be a mountain or a valley or something the player created. So what I have to do is I have to cast a ray at the ground and figure out where the ray hits, and put the player a little bit above where the ray hit.

The problem with this is my chunks generate in a separate thread. So if I immediately cast a ray, the mesh won’t be generated quite yet and the ray won’t hit anything. That’s not helpful.

I also don’t like the idea of delaying it by a fixed amount of time before trying the ray. That doesn’t feel like a good solution and it may not work on some devices.

So I figured I’d set up an event from my chunks that get triggered when the chunk is done loading. So I basically use meshCollider.sharedMesh = [mesh I calculated in another thread]. I do this on the main thread, as Unity enforces that. And after that’s all done, I trigger my event.

Then using that event I can say: okay, the chunk is generated, now I can cast my ray and position the player properly.

But it seems to not be working that way. I cast my ray after my event triggers, and it hits nothing! I tested delaying the raycast by a second, and it hit something just fine.

So what’s going on? My guess is that the process of updating the mesh that happens when I use meshCollider.sharedMesh = [mesh I calculated] actually does work on other threads. And therefore it’s still not actually done by the time I trigger my event.

Which leads to my question. Is there any way to know when the mesh has been fully calculated and is done, so I know when I can cast my ray?

Thank you for your help!

No functions are asynchronous unless specifically mentioned in the docs, and nothing like this is ever done in other threads since that would leave the engine in an indeterminate state. When you assign the mesh nothing else can happen until it’s done computing. I expect that it would be registered with the physics engine at the start of the next physics frame.