Copying Physics Joints during Runtime

I am working on a script that allows me to dynamically slice objects during runtime. When an object is sliced, it is split into two separate GameObjects. I would like to preserve existing Physics Joints as well. For instance, if an object has a spring joint on top and a fixed joint on bottom, I want to be able to split the object in two (creating two new GameObjects) and have the spring joint copied to the top object and fixed joint to the bottom object. The desired effect would be for the top object to get launched by the spring while the bottom stays fixed.

Since Unity doesn’t allow copying components, I’m stuck on how to implement this. I could create a method for each joint type that copies the values over. I’ve also seen solutions using Reflection but I’d prefer to avoid this because it is slow and seems unsafe.

Is there another way I’m not thinking of?

Eh, it’s messy for sure. Here’s a possible way that sounds really messy but might have some “it might reveal something interesting” basis:

  • remove all the colliders from the object and its hierarchy
  • clone the entire object with Instantiate
  • reattach colliders and geometry of the proper size / shape to each side

I think Unity will recompute weight and center of gravity and tensor moments for each RB with the new colliders.

If the new colliders overlapped you could expect a violent physics jerk, so make sure your slice is cleanly separated.

1 Like

I’ll be honest, your idea didn’t sound great at first but it ended up actually working perfectly. Previously I was creating new objects from scratch by adding components via script. But cloning the existing object and updating the mesh & rigid body properties only required modifying a few lines of code. For each cloned object, I’m now able to iterate over each joint and see if its anchor position lies within the new volume. Works like a charm! I can slice away and only the mesh connected to the spring stays connected while the other chunks falls to the floor. Thank you for your help!

1 Like