- Home /
RaycastHit2D should be child object but is parent
Hi! I have a child object that is rendered on top of its parent object. They both have trigger colliders.
I'm trying to use raycast to detect when I click the child object, but the RaycastHit2D returned has the collider of the parent object and not the child.
private RaycastHit2D hit;
void Update()
{
if (Input.GetMouseButtonUp(0))
{
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
hit = Physics2D.Raycast (worldPoint, Vector2.zero);
Debug.Log(hit.collider + " using raycast");
//Debug.Log(hit.transform.gameObject.name + " using raycast");
//Debug.Log(hit.collider.transform.name + " using raycast");
//Debug.Log(hit.collider.name + " using raycast");
// All commented outs above give the same result as the one not commented out
}
}
However, using the following method in a script on the child object correctly returns the child object.
void OnMouseUpAsButton()
{
Debug.Log (gameObject.name + " from OnMouseUpAsButton");
}
So to be clear, when I run the game and click the child object, the Debug.Logs print:
"childObject from OnMouseUpAsButton"
"parentObject using raycast"
Answer by hatake3 · Sep 17, 2014 at 10:39 AM
For some reason, the raycast didn't hit the child object at all (yes, I do have 'Raycasts Hit Triggers' checked, and not using IgnoreRaycast layer), even if I moved it away from other objects. Only when I created a new identical object did the raycast hit. It's weird, because the old object and the newly created object had exactly the same configurations in the inspector.
Your answer
Follow this Question
Related Questions
Identifier expected on equals symbol 1 Answer
Physics2D.Raycast returns incorrect normal when casting from inside collider 1 Answer
Raycast 2D hits sprite with collider, but returns error when not hitting any collider 2 Answers
UI button and raycast script that I have made both aren't working to change my scene 1 Answer
Unity Physics2D.Raycast always returns “the invoker” as hit 2 Answers