I have created a rope bridge which consists of GameObjects with rigidbodies connected together with joints. Looks and works well. I have the joints’ breakForce set and when the bridge is hit with a strong enough force some of the joints break and the bridge falls apart as expected. When examining the objects in the editor interactively, the HingeJoints originally on the objects where the break occurred are gone. (as expected).
At certain points in the game I reset various GameObjects in the scene back to their original state. I record their original state on Awake as such:
void Awake()
{
hinges = gameObject.GetComponents<HingeJoint>();
hingeParams = new HingeParams[hinges.Length];
for (int i = 0; i < hinges.Length; i++)
{
hingeParams[i] = new HingeParams
{
connectedBody = hinges[i].connectedBody,
anchor = hinges[i].anchor,
axis = hinges[i].axis,
autoConfigure = hinges[i].autoConfigureConnectedAnchor,
useSpring = hinges[i].useSpring,
spring = hinges[i].spring,
breakForce = hinges[i].breakForce,
breakTorque = hinges[i].breakTorque
};
}
ResetPosition = gameObject.transform.position;
ResetRotation = gameObject.transform.rotation;
rb = gameObject.GetComponent<Rigidbody>();
ResetVelocity = rb.velocity;
ResetAngularVelocity = rb.angularVelocity;
}
And then when I want to reset the objects:
gameObject.transform.position = ResetPosition;
gameObject.transform.rotation = ResetRotation;
rb.velocity = ResetVelocity;
rb.angularVelocity = ResetAngularVelocity;
for (int i = 0; i < hinges.Length; i++)
{
if (hinges[i] == null)
{
print("Joint gone");
hinges[i] = gameObject.AddComponent(typeof(HingeJoint)) as HingeJoint;
hinges[i].connectedBody = hingeParams[i].connectedBody;
hinges[i].anchor = hingeParams[i].anchor;
hinges[i].axis = hingeParams[i].axis;
hinges[i].useSpring = hingeParams[i].useSpring;
hinges[i].spring = hingeParams[i].spring;
hinges[i].breakForce = hingeParams[i].breakForce;
hinges[i].breakTorque = hingeParams[i].breakTorque;
hinges[i].autoConfigureConnectedAnchor = hingeParams[i].autoConfigure;
}
}
Everything works well, and I have my rope bridge back and functioning again. However, upon breaking the bridge a second time, the bridge visually breaks, but at the break the newly created HingeJoints are NOT destroyed. Should the bridge break at one of the original hingejoints they will be gone as normal, but none of the new AddComponent() hingejoints is ever destroyed.
Trying to reset the bridge a second time fails as the hingejoints still appear to be connected to the next rigidbody in the chain. I decided to try and catch these events in OnJointBreak(). As displayed in the editor though, this event fires for any originally placed hingejoint the breaks, but never fires for any of the newly minted hingejoints that despite functionally and visibly breaking are never destroyed.
Other than reinstantiation the whole bridge each time (which would break the game’s design) any other ideas on recreating normally breakable hingejoints?