I wrote a script to instantiate a prefab in place of a destroyed object and it works just fine, but now I want that same code to randomly choose from one of four prefabs. I would prefer to not define the prefabs in the script itself, and leave it to be defined through public GameObject’s, just like it already is. I need the script to stay as universal as possible so it can be used on all destructible objects, only requiring me to replace the prefabs each time it’s added to a new object. I’m just drawing a blank, I know it’s a simple solution, I just can’t think of how to do it for the life of me. Thanks in advance.
using UnityEngine;
using System.Collections;
public class Destructible : MonoBehaviour {
public GameObject debrisPrefab;
public GameObject debrisPrefab1;
public GameObject debrisPrefab2;
public GameObject debrisPrefab3;
public float destroyImpact = 20.0f;
void OnCollisionEnter( Collision collision ) {
if( collision.relativeVelocity.magnitude > destroyImpact ) {
DestroyMe();
}
}
void DestroyMe() {
if(debrisPrefab) {
Instantiate(debrisPrefab, transform.position, transform.rotation);
}
Destroy(gameObject);
}
}
An example of the code use is:
This code is attached to a brick wall, which is then destroyed. I then have 4 different “destroyed_brick_wall_number” prefabs I want the engine to choose from when replacing the original “brick_wall” object. I currently have it set to use “destroyed_brick_wall_1” in this example and it works fine; but every destroyed wall looks the same. I want them to look different upon destruction, at least a little bit.