Search Unity

Problem with destroying instanciated enemies

Discussion in 'Scripting' started by Chill_Penguin, Aug 10, 2017.

  1. Chill_Penguin

    Chill_Penguin

    Joined:
    May 6, 2015
    Posts:
    13
    I have some code to destroy an object when it gets hit by a bullet, and a simple enemy prefab.
    If I put a few of these in the scene in the editor, they will be destroyed just fine. But if they are instantiated by another object they won't interact with the bullets, even though the prefab is the same.

    The code related to destroying the enemies:
    Code (CSharp):
    1. public GameObject explosion;
    2.  
    3. void OnTriggerEnter(Collider other)
    4.     {
    5.         if (other.tag == "Bullet")
    6.         {
    7.             Instantiate(explosion, transform.position, Quaternion.identity);
    8.             Destroy(other.gameObject);
    9.             Destroy(this.gameObject);
    10.         }
    11.     }
    I don't know why this only works for manually created enemies, if anyone could explain why that would be great :)
     
  2. phoda

    phoda

    Joined:
    Nov 11, 2014
    Posts:
    384
    maybe check that prefab is updated. delete prefab and create new with object in editor that works. also how you instantiate may help as this code seems fine
     
  3. Chill_Penguin

    Chill_Penguin

    Joined:
    May 6, 2015
    Posts:
    13
    Replaced the prefab, still not working. Here's the code to instantiate:
    Code (CSharp):
    1. private int number = 0;
    2.     public GameObject enemy;
    3.  
    4.     void Update ()
    5.     {
    6.         number = Random.Range(1, 100);
    7.         if (number == 50)
    8.             Instantiate(enemy, new Vector3(0, 0, 185.0f), Quaternion.identity);
    9.     }
    Please excuse the sloppy random enemy spawner thing, it's still a test
    The enemy gameobject is the one we were talking about earlier, and the one I have replaced in the editor
     
  4. Chill_Penguin

    Chill_Penguin

    Joined:
    May 6, 2015
    Posts:
    13
    It's working now, not sure what I did. A lot of Debug.Log but the only code I changed was the 185.0f to 160.0f so it could be that the bullets go so fast, they kind of skip over the area around the enemy at 185.0f but this is basically just speculation. Gonna make the hitbox longer just in case.