So in the game I am creating, I am destroying a subobject (e.g an arm) which has a SkinnedMeshRenderer and then creating a new object which should have the same SkinnedMeshRenderer (new object will be attached to the same armature), but after doing the following line of code:
I am getting the following error:
Destroying components immediately is not permitted during physics trigger/contact, animation event callbacks, rendering callbacks or OnValidate. You must use Destroy instead.
This happens on collision.
Regardless of your error, do you know that if the mesh you’re trying to render is an actual skeletal animated mesh, the SkinnedMeshRenderer needs to have the proper bone array. This array is created during import and stored inside the SkinnedMeshRenderer. It’s the glue between the Mesh and the bone structure. It has to match 100%.
Note: Just because to seperate meshes have the same bone structure does not mean that the order of the bones in the bones array is the same. This could even happen when the mesh is reimported. So if you have multiple seperate skinned meshes with the same bone structure, you have to remap the bones anyways. Since this is quite a bit of work anyways, there’s usually no need to destroy and re-add the SkinnedMeshRenderer. You just have to replace the sharedMesh and set the bones array correctly.
To address your error, it’s hart to tell how this error was actually produced without any context. From the error message we can assume that you do this inside:
physics trigger/contact, animation
event callbacks, rendering callbacks
Those are all callbacks from within certain internal processes in Unity and you should not destroy objects in those callbacks. You could delay the actual replacement with a coroutine that waits one frame for the next update.
It’s possible that when you use the normal “Destroy” which usually delays the destruction until the end of the current frame, when you immediately add a new component to the same place, Unity is forced to remove the old one immediately. So it would make sense that Destroy alone works, but Destroy with adding the new object does not.
Though there were a lot of speculations here since we don’t really have much context.
ps: If you need a way to remap the bones properly, your bones need tohave unique names and you can use the extension method shown over here.