To create a destructible object, follow these steps:
- Import the normal and shattered objects to Unity. In our example, we have an object called Ball and the other one is called BallFractured.
- Drag and drop both objects into the scene.
- Select all child game objects (pieces) of the BallFractured game object. Add the Rigidbody and Mesh Collider components to them. Set the Mesh Collider to Convex.
- Create a prefab from the BallFractured game object (containing all the pieces).
- Select the Ball game object and add a Rigidbody and a Sphere Collider to it (or another type, depending on the shape of your object).
- Write a new C# script and call it SpawnFracturedObject.cs. In this script, we have a void Fracture() function that spawns a fractured game object prefab (our BallFractured), applies velocity to all its pieces, and destroys the main object (Ball):
void Fracture() { GetComponent<Collider>().enabled = false; GameObject fracturedObject = (GameObject)GameObject.Instantiate(fracturedObject Prefab, transform.position, transform.rotation); Rigidbody[] rigidBodies = fracturedObject.GetComponentsInChildren<Rigidbody> (); for (int i = 0; i < rigidBodies.Length; i++) { rigidBodies[i].velocity += lastRigidBodyVelocity; } Destroy(gameObject); }
- The void Fracture() function is called when our main object collides with anything:
void OnCollisionEnter(Collision col) { Fracture(); }
- The Ball's velocity is saved every frame to the float lastRigidBodyVelocity variable (in the FixedUpdate() function):
void FixedUpdate () { lastRigidBodyVelocity = rb.velocity; }
- Assign the script to the Ball game object and drag the BallFractured prefab onto the Fractured Object Prefab field in the Inspector.
- Play the game to see the effect:
Before and after collision