Search Unity

Function to destroy all objects with tag

Discussion in 'Scripting' started by EmerickGrimm, Dec 14, 2019.

  1. EmerickGrimm

    EmerickGrimm

    Joined:
    Mar 18, 2018
    Posts:
    2
    I'm trying to make a function that should destroy all objects with tag once.

    Here is my script (It's not working, unity just crashed).

    Code (CSharp):
    1. public void DestroyAllEnemy()
    2.     {
    3.         while(GameObject.FindGameObjectsWithTag("Enemy")!= null)
    4.         {
    5.             Destroy(GameObject.FindWithTag("Enemy"));
    6.         }
    7.         return;
    8.     }
    9.  
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    4,971
    You'll want to store the results in a collection, then loop through and destroy each one.
     
  3. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    431
    Don’t use while loops. Only if you’re certain that it’ll be broken at some point.

    use the method FindGameObjectsWithTag and store it into a variable.
    Then use a reversed for loop to cycle through the objects and call Destroy.
     
unityunity