C#: Upon Explosion; I want to replace one Prefab for another

I have two prefabs for the same character. One is made up of one mesh while the other is modeled into a bunch of pieces.

When I blow up the character, I want to destroy the solid mesh object and instantiate the one with multiple pieces.

I’m thinking this should be fairly easy to do.

2 Answers

2

Yeah, very easy.

I would first instantiate the one with multiple pieces, so you can use the location of the first one as a reference point. so…

//to create the multiple piece gameobject
//solidMeshObject is a reference to your first character.
//"multiplePieces" is the name of your prefab with multiple pieces.. it needs to be in your resources folder.
Instantiate ( Resources.Load( "multiplePieces" ), solidMeshObject.transform.position, solidMeshObject.transform.rotation );

//then destroy the original, since you no longer need it
Destroy( solidMeshObject ); 

You could even take it further and put each separate piece in an array of GameObjects… add a rigidbody and collider and a random force to explode em all into separate directions.

When I try: Destroy( solidMeshObject ) It get error: Destroying assets is not permitted to avoid data loss. I see people use Destroy to remove an object from the scene all the time.......

–

Show the line where you set your game object to destroy as solidMeshObject. Destroy can only destroy a gameObject. You need to say "GameObject solidMeshObject = ..." somewhere.

–

Here’s a solution that works

yup, that's exactly what I said

–