Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[Solved] Question - Destroy objects tagged.

Discussion in 'Scripting' started by kholyphoenix1, Nov 15, 2015.

  1. kholyphoenix1

    kholyphoenix1

    Joined:
    Apr 17, 2015
    Posts:
    57
    Hello,

    I need a "script" that destroys itself when it collided with the character and the other objects with the name tag "BlockObject"

    ---

    Script:

    #pragma strict

    //Variável
    var player : Transform;

    function Start () {

    }

    function Update () {

    }

    function OnCollisionEnter(collision : Collision) {

    if(collision.transform == player) {

    Destroy (GameObject.FindWithTag("BlockObject"));
    Destroy (gameObject);

    }

    }
     
  2. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,260
    You need to get the list of objects that have that tag.

    Code (CSharp):
    1. GameObject[] objectsToDestroy = GameObject.FindGameObjectsWithTag("BlockObject");
    2. foreach (GameObject go in objectToDestroy)
    3. {
    4.     Destroy(go);
    5. }
     
    kholyphoenix1 likes this.
  3. SteveJ

    SteveJ

    Joined:
    Mar 26, 2010
    Posts:
    3,085
    You don't want to destroy objects in a collection that you're currently iterating through.

    @kholyphoenix1 - I might be misinterpreting what you're asking, but can't you just check that the object you're colliding with is either the player OR an object with the tag that you're looking for, and if it is, destroy yourself? Something like:

    Code (csharp):
    1.  
    2. if ((collision.transform == player) || (collision.gameObject.tag == "whatever"))
    3. {
    4.     Destroy (gameObject);
    5. }
    6.  
    7.  
     
    kholyphoenix1 likes this.
  4. kholyphoenix1

    kholyphoenix1

    Joined:
    Apr 17, 2015
    Posts:
    57
    Hello again.
    My intention is to destroy the two objects.
    For example if I caught a key I want the gates are broken so that the path is released.

    I'll test the code and wanted to thank you for explaining me.
    Thanks a lot!!!

    ---

    Solved!
    Thanks a lot!
     
    Last edited: Nov 16, 2015
  5. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,260
    You can't modify any collection that you are iterating through. It will still iterate through the collection without a hitch. We are not modifying the collection itself, only setting a flag on an item in the collection(Destroy waits till the end of the frame to do the actual destroy). We could even make the item null and still not a problem. It would blow up when compiling if we were to remove or add to that collection during the loop.
     
    kholyphoenix1 likes this.