- Home /
adding mesh collider in run time slow?
i would need an advice about adding mesh colliders in run time. this makes size of the build much smaller but it takes some time to add a collider, especially mesh colliders.
i wanted to do it in the coroutine but it somewhat hangs, but without coroutine it freezes. here is the code to add mesh colliders to transforms:
void Prepare(){
StartCoroutine(StartPrepare());
}
IEnumerator StartPrepare()
{
Transform[] objects = prefabToPrepare.GetComponentsInChildren<Transform>();
for(int i = 0; i < objects.Length; i++)
{
if(objects[i].gameObject.renderer)
{
objects[i].gameObject.AddComponent<MeshCollider>();
Debug.Log("i: " + objects[i].name);
yield return null;
}
}
}
i am doing something wrong here, uncommenting add mesh collider line debug statements are printed, adding box collider is much faster. meshes are not that high poly...?
Answer by Fattie · Sep 22, 2012 at 01:54 PM
It simply takes a long time to "import" as it were, a mesh.
(Please note .. as Eric critically points out below, the problem is the mesh collider, not the mesh-that-draws-stuff.)
You "just can't" - that's it. You're doing nothing wrong, it's just an inherent limitation of today's pipeline, hardware and software.
If you build something dynamically, say a Dragon, that's great. At start-up time or between scenes you can "import" that new mesh you've created dynamically.
But the current state of the art 3D game pipeline - you just can't "import" your new mesh in real time. That's that.
To be clear, the actual calculation time for you to make a mesh is nothing. The problem is "importing" it to the pipeline. (To be clear, issues like foreach, coroutines, etc, are totally irrelevant.)
There are many long-winded discussion about this basic limitation on this site, eg
http://answers.unity3d.com/questions/315059/how-to-improve-performance-while-generating-extrud.html
"Basically putting new mesh in to a scene is ... slow ! it just takes a long time to cycle in the new mesh. That's that really."
Hope it helps, sorry for the bad news ! :O
Putting a new mesh in the scene is not slow. Adding a mesh collider, however, is, because there are some heavy pre-processing calculations done by PhysX, so that it will perform faster.
Answer by RunSwimFly · Feb 26, 2013 at 04:35 AM
Late answer but I found that chopping my meshes up before adding a mesh collider to them significantly reduced the overall time required. In my case this automatic subdivision was relatively simple as it was for user generated heightfields on a regular grid.
Answer by vikingfabian-com · Jun 30, 2014 at 06:08 PM
My solution was to recycle the GameObjects
put them in a Stack
Set Renderer.Enabled to false
pop the stack when you need an object, if the stack is empty you create a new GO.