Search Unity

How to destroy 2 gameObject when they overlap and player tap on them

Discussion in 'Animation' started by sulaimankhan21, Jul 2, 2017.

  1. sulaimankhan21

    sulaimankhan21

    Joined:
    Jul 2, 2017
    Posts:
    4
    Hello i am trying to destroy 2 GameObjects when they overlap and at that time if player touch them then both of them get destroy. Kindly help me i m trying this from one month.
     
  2. phaem

    phaem

    Joined:
    Jan 5, 2015
    Posts:
    76
    Add colliders and rigibodies to your objects. Set rigibodies isKinematic=true in Inspector. Set colliders as triggers in Inspector.

    Then check out docs for OnTriggerStay method. This way you'll know when object are in touch with each other an you can save a reference to another one in both of them, since both will receive the event if their colliders overlapping this frame. Then you'll need the OnTriggerExit to clear references when they stop overlapping.

    To detect a touch you may use OnMouseDown or OnMouseUpAsButton or OnMouseUp method - try them all and see the difference in their behaviour. Simply check if overlapping reference isn't null, and if so, destroy both game objects using Destroy(gameObject) and Destroy(overlappingObject) calls.
     
    sulaimankhan21 likes this.
  3. LabradorLover

    LabradorLover

    Joined:
    Jul 3, 2017
    Posts:
    1
    Why is this script not working?

    void OnCollisionEnter2D(Collision2D col)
    {
    if (col.gameObject.tag == "Hazard")
    {
    Destroy(gameObject);
    }
    }

    This is applied to my player sprite, and the sprites with the tag of "Hazard" are lava sprites. My character is not getting
    destroyed when he touches the lava. Please help!
     
  4. phaem

    phaem

    Joined:
    Jan 5, 2015
    Posts:
    76
    This script may not work by the following reasons.

    1. There are no rigidbody2d component on either character or lava. It must be there in order to detect collisions, unity requirement.
    2. There are no collider on one or both objects or they're marked as triggers.
    3. 3D colliders are used instead of 2D. This is different systems, they do not work with each other, use 2D -OR- 3D.
    4. Other game object is not tagged as "Hazard".
    5. Collision layers prohibits players from colliding lava - check your collision layers matrix in project settings.

    I suggest you add Debug.Log outside the if block and another one inside to see if the collision happens and if the other object's tag match or not.

    Btw, use CompareTag function instead of == operator, it's a little optimized.
     
  5. sulaimankhan21

    sulaimankhan21

    Joined:
    Jul 2, 2017
    Posts:
    4
    Thanks a lot this solved my problem. :)
     
unityunity