Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Need help with destroying 2d gameobject with raycast2d C#

Discussion in 'Scripting' started by Maxweight, Nov 30, 2014.

  1. Maxweight

    Maxweight

    Joined:
    Nov 2, 2014
    Posts:
    18
    Im trying to figure out how to destroy gameobject(ball) with other gameobject(ant) on mouseclick. I have 2 objects and both have Rigidbody 2d + Circe collider 2d. This script is attached to gameobject(ant)

    this destroys object even im not clicking it on top of the ant gameobject so it destroys from everywhere i click.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class DestroyOnClicked : MonoBehaviour {
    5.  
    6.     public GameObject ant;
    7.  
    8.     void FixedUpdate ()
    9.     {
    10.         if (Input.GetMouseButtonDown(0))
    11.         {
    12.             RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    13.            
    14.             if(hit.collider != null)
    15.             {
    16.                 if(hit.collider == gameObject.collider2D);
    17.                 {
    18.                     Destroy(gameObject);
    19.                 }
    20.             }
    21.         }
    22.     }
    23. }
    24.  
     
  2. Maxweight

    Maxweight

    Joined:
    Nov 2, 2014
    Posts:
    18
    ok i found solution. I removed collider from ball and ant changed to is trigger