Search Unity

Certain amount of hits replaces object with destroyed version

Discussion in 'Scripting' started by rudigreig, Mar 17, 2019.

  1. rudigreig

    rudigreig

    Joined:
    Dec 11, 2018
    Posts:
    50
    I wanted to create an enemy vehicle that when hit 8 times (seconds) gets replaced with a destroyed version, can anyone help me? (I tried instantiate which is why I have public GameObject object2; )
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class VehicleDamage8 : MonoBehaviour
    5. {
    6.  
    7.     public int hitsNeeded = 8;
    8.     public int hitsTaken;
    9.  
    10.     public GameObject object2;
    11.  
    12.     private void OnTriggerEnter(Collider other)
    13.     {
    14.         if (other.CompareTag("Player"))
    15.         {
    16.             hitsTaken += 1;
    17.  
    18.             if (hitsTaken >= hitsNeeded)
    19.             Destroy(gameObject);
    20.         }
    21.     }
    22. }
     
  2. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
    That should work I think, you just need to add the instantiate call (perhaps use a coroutine, and have it wait a fraction of a second, though not really necessary, it might prevent the newly spawned destroyed vehicle from clipping and hitting the regular vehicle). You can just enclose that if(hitsTaken... part with curly brackets ( these: {} ) and then put the instantiate call in there, and make its position and rotation match that of the vehicle.
     
  3. rudigreig

    rudigreig

    Joined:
    Dec 11, 2018
    Posts:
    50
    It works, thanks mate, if i do SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); is it possible i can delay the scene change by a few seconds?
     
  4. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
    rudigreig likes this.