0

In the code below, my issue is the parent object has two child objects, so whenever I click any child object, it is recognized twice. How can I get the mouse click to recognize only the child game object that is clicked and not both? Note that the parent object was made with an empty script. Please check the code below:

void Update() {
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log("Pressed left click, casting ray.");
        CastRay();
    }
}

void CastRay() {
   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   RaycastHit hit;
   if (Physics.Raycast(ray, out hit, 100)) {
       Debug.DrawLine(ray.origin, hit.point);
   }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115

1 Answers1

0

If you have your script in each child, they will each be generating a ray and both recognizing that an object is hit (thus showing it twice). What you want to do instead is have one script in the parent. You can have this script check for the name of the gameobject that the ray hits in order to determine what action should occur.

Edit: Since you have a 2D scene you will need to do the following:

void CastRay()
{
    RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    if (hit.collider != null && hit.collider.gameObject.name == "object1")
    {
        // do something for gameobject with name of object1
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
ryeMoss
  • 4,303
  • 1
  • 15
  • 34
  • I put a Log in the nested if in `CastRay` but it doesn't print. My child objects have polygon colliders, I don't know if that should be affecting the result in anyway. – SuperHyperMegaSomething Aug 24 '17 at 15:26
  • Is this a 2d or 3d scene? If you have a 2d polygon collider you will need to cast a 2d ray. – ryeMoss Aug 24 '17 at 15:47
  • It's a 2d scene. I changed `RaycastHit hit;` to `RaycastHit2D hit;` and `Physics.Raycast` to `Physics2D.Raycast`, but I am getting the following error: `error CS1502: The best overloaded method match for 'UnityEngine.Physics2D.Raycast(UnityEngine.Vector2, UnityEngine.Vector2, float)' has some invalid arguments` pointing to the line `if (Physics2D.Raycast(ray, out hit, 100)`. Not sure how to get that solved. – SuperHyperMegaSomething Aug 24 '17 at 16:09
  • I've edited my answer for a 2D scene. – ryeMoss Aug 24 '17 at 16:47