Search Unity

Destroy Objects with tag

Discussion in 'Scripting' started by Jens, Aug 31, 2007.

  1. Jens

    Jens

    Joined:
    Aug 14, 2007
    Posts:
    18
    Hi!

    I need to write a function that destroys
    any object in the scene with a specific tag attached.
    This code:

    function destroyxyz () {
    var tobedestroyed = GameObject.FindGameObjectsWithTag ("xyz");
    for (var go : GameObject in tobedestroyed) {Destroy (go);}
    }

    .. adapted from a script example, does nothing noticeable.
    Does anyone have an idea?

    Thanx

    Jens
     
  2. drJones

    drJones

    Joined:
    Oct 19, 2005
    Posts:
    1,351
    it returns a list so you need to put the result in an array:

    var tobedestroyed : GameObject [];

    from here:

    http://unity3d.com/Documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html

    EDIT: actually to be honest from that link i'm not sure what's happening in the top part of the script i didn't know it could be done that way (and it looks like that's what you were trying) - maybe someone else can help with that but the array method works ; )
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    When you do it that way, the variable is automatically typed as an array, so you don't actually have to specify "GameObject[]". (Remember that nice type inference. :) )

    I'm not really sure why Jens' code isn't working. Should be fine, unless you've maybe entered the tag wrong (don't forget about case sensitivity) or else the objects aren't actually assigned the tag for some reason.

    --Eric
     
  4. drJones

    drJones

    Joined:
    Oct 19, 2005
    Posts:
    1,351
    ahh... good to know. thanks eric ; )
     
  5. Jens

    Jens

    Joined:
    Aug 14, 2007
    Posts:
    18
    with the variable defined as an array, it works fine.

    var tobedestroyed : GameObject [];

    Thanks for the help!

    Jens :eek: :D
     
  6. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    That's weird, here's some code I wrote yesterday:

    Code (csharp):
    1.     var ships = GameObject.FindGameObjectsWithTag("Ship");
    2.     for (var ship in ships) {
    3.         Destroy(ship);
    4.     }
    And it works.... But hey, whatever. ;)

    --Eric
     
  7. Jens

    Jens

    Joined:
    Aug 14, 2007
    Posts:
    18
    Code (csharp):
    1. var tobedestroyed : GameObject[];
    2. tobedestroyed = GameObject.FindGameObjectsWithTag ("Robot");
    3. for (var go : GameObject in tobedestroyed)  {Destroy (go);}
    4.  
    That's my actual code.

    Your's is shorter and easier to read
    (and it works in my script, too.)
    I think I will use your's, it's better.

    :wink:

    Jens