Search Unity

Destroy objects without using rigidbody

Discussion in 'Scripting' started by Krodil, Dec 8, 2011.

  1. Krodil

    Krodil

    Joined:
    Jun 30, 2010
    Posts:
    141
    hey,
    as you might have guessed, I wish to have an area where objects with a certain tag gets deleted.
    Now I use
    Code (csharp):
    1. function OnCollisionEnter ( other : Collision )
    2. {
    3.     if (other.gameObject.tag == "object")
    4.     {
    5.         Destroy(other.gameObject);
    6.     }
    7. }
    But it requires the objects to have rigidbodies, which I would like to avoid.
    Do you have some tips for me?
    Krodil
     
  2. ShadoX

    ShadoX

    Joined:
    Aug 25, 2010
    Posts:
    260
    I'm probably wrong, but isn't there a way to get the name of the collider? In which case you could simply check that instead of a tag?
     
  3. spinaljack

    spinaljack

    Joined:
    Mar 18, 2010
    Posts:
    992
  4. jheiling

    jheiling

    Joined:
    Sep 28, 2010
    Posts:
    65
    You don't need a Rigidbody, you just need a Collider.
     
  5. Krodil

    Krodil

    Joined:
    Jun 30, 2010
    Posts:
    141
    If I have this code and remove the rigid body from the instantiated object, nothing happens.
    Code (csharp):
    1. //For the garbage pit
    2.  
    3. // Immediate death trigger.
    4. // Destroys any colliders that enter the trigger, if they are tagged object.
    5.  
    6. function OnTriggerEnter ( other : Collider )
    7. {
    8.     if (other.gameObject.tag == "object")
    9.     {
    10.         Destroy(other.gameObject);
    11.     }
    12. }
    The object is supposed to be removed when I drag it into the garbage pit. It is tagged with 'object'.
    Should it be in an update or something?
     
  6. jheiling

    jheiling

    Joined:
    Sep 28, 2010
    Posts:
    65
    You are right, it needs a Rigidbody. Sorry, my mistake.

    Like spinaljack said, you could use OverlapSphere:

    Code (csharp):
    1. void Update()
    2. {
    3.      foreach(Collider c in Physics.OverlapSphere(transform.position, radius))
    4.   {
    5.     if(c.CompareTag("object")) Destroy(c.gameObject);
    6.   }
    7. }
    Sorry for the C#, should be easy enough to translate to unity script
     
  7. Krodil

    Krodil

    Joined:
    Jun 30, 2010
    Posts:
    141
    thanx jheiling and SpinalJack, it was a very easy implementation and now I dont HAVE to use rigids.
     
  8. codenameone

    codenameone

    Joined:
    Jun 29, 2016
    Posts:
    1
    Thanks alot. Saved me couple of hours.
    Here's a C# code for 2D

    private void Update()
    {
    transform.position = new Vector3(player.position.x - 40, player.position.y, 0f); //object moves with player

    foreach (Collider2D c in Physics2D.OverlapBoxAll(transform.position, new Vector2(10, 1), 90f)) //get all the colliders
    {
    if (c.CompareTag("Wall") || c.CompareTag("Ground"))
    Destroy(c.gameObject);
    }
    }