using System.Collections; using UnityEngine; public class ObjectBehaviour : MonoBehaviour { //Variables Vector3 DestroyPtPos; Rigidbody rb; GameObject[] pieceList; //array of debris after explode Renderer rd; //public variables public float speed = 2f; // Speed public float cubeSize = 0.15f; //size of debris after explode public int noOfPieces = 30; //no of debris void Start() { //get Destroy position GameObject destroyPt = GameObject.Find("DestroyPoint"); DestroyPtPos = destroyPt.transform.position; //get rigidbody rb = GetComponent(); //get renderer rd = GetComponent(); } // Update is called once per frame void Update () { //make objects fly to camera // takes 5 sec for it to reach the camera transform.position = Vector3.MoveTowards(transform.position, DestroyPtPos, speed * Time.deltaTime); } private void OnTriggerEnter(Collider other) { //if object collide DestroyPoint if (other.gameObject.name == "DestroyPoint") { print("collided"); //to make object untouchable rb.isKinematic = false; rb.detectCollisions = false; //make object disappear rd.enabled = false; //explode after it touches DestroyPoint explode(); //clear debris after 1 sec of explode StartCoroutine(delPieces()); //decrease totalobjects count since 1 is destroyed Spawner.objectDestroyed = true; } } void explode() { //For loop to create 30 pieces as debris after explode int x = 50; pieceList = new GameObject[noOfPieces]; for (int i = 0; i < noOfPieces; i++) { pieceList[i] = createPiece(x); x *= -1; } } public GameObject createPiece(int x) { //create piece GameObject piece; piece = GameObject.CreatePrimitive(PrimitiveType.Cube); //set piece position and scale and rotation piece.name = "Debris"; piece.transform.position = transform.position + new Vector3(cubeSize, cubeSize, cubeSize); piece.transform.localScale = new Vector3(cubeSize, cubeSize, cubeSize); piece.transform.localEulerAngles = new Vector3(cubeSize * x, cubeSize * x, cubeSize * x); //add rigidbody and set mass piece.AddComponent(); piece.GetComponent().mass = 0.05f; //add color piece.GetComponent().material.color = new Color(1, 1, 1, 1); return piece; } private IEnumerator delPieces() { //Clear debris after 1 seconds yield return new WaitForSeconds(1); foreach (GameObject item in pieceList) { Destroy(item); } pieceList = new GameObject[0]; yield return new WaitForSeconds(5); Destroy(gameObject); } }