Search code examples
c#triggersunity-game-enginedestroy

Trigger...Spawn...Destroy Unity 3D


Im running into a little problem. As soon as I hit a trigger I want an enemy to spawn. I only want one enemy on the field. Now when I hit the trigger again I want that enemy that is on the field to destroy it self while the next enemy is about to spawn. Any ideas on how to do so? Do I use a "Destroy" Assignment on this? Heres what I have:

 public GameObject Enemy;
 public float mytimer;


 void Start()
 {
     GameObject player = GameObject.Find("Player");
 }

 void spawnEnemy() {
     Transform enemy;
     GameObject enemySpawnPoint =      GameObject.Find("EnemySpawn");
     enemy =  Instantiate(Enemy,enemySpawnPoint.transform.position,enemySpawnPo int.transform.rotation) as Transform; 
 }

 void OnTriggerEnter(Collider other)
 {
     if (other.gameObject.name == "EnemyTrigger") {
         mytimer = Random.Range(0,10);
         Invoke("spawnEnemy", mytimer);
         Debug.Log("Spawn Normal");

         }
     }

     }

Solution

  • You can store your enemy into a private variable and destroy it every time before instantiating a new one. This way you will have only one of them.

    private GameObject enemy = null;
    void spawnEnemy() {
        if(enemy != null){
            Destroy(enemy);
        }
        GameObject enemySpawnPoint =      GameObject.Find("EnemySpawn");
        enemy =  Instantiate(Enemy,enemySpawnPoint.transform.position,enemySpawnPo int.transform.rotation) as GameObject; 
    }