- Home /
Clicking on child executes parent script when Rigidbody2D present?
Hi
I have two gameObjects with Box Colliders set to trigger. Each gameObject has its own script, basically just this:
void OnMouseDown() {
Debug.Log (gameObject.name);
}
when I click on the objects it prints the name of the object being clicked. Since I want both to move together I put one object as a child of the other and still I get the correct object name when clicking the parent or the child. However, once I add a Rigidbody2d component to the parent, clicking the child prints the parent name. Is this the way it is supposed to work? If so, how do i probe for which gameObject was actually pressed?
Thanks
Can you post a picture of exactly what it is you're clicking with their colliders showing please.
Well if there are 2 colliders, 1 being on the parent and child, then it makes sense that both will get executed. Perhaps, you should have something deter$$anonymous$$e which one to exactly use or temporarily disable the parent rigidbody.
You could also try to replace On$$anonymous$$ouseDown with an Input check in Update, raycast at that point and get the script of the object you casted against. It will return the actual collider, not the parent or something.
Answer by Kiwasi · Feb 28, 2015 at 09:46 AM
This is normal behaviour. All child colliders are considered to be part of the rigidbody they are parented too. Events like OnTriggerXXX, OnCollisionXXX and OnMouseXXX will be transmitted to the rigidbody.
Another side effect of this is that rigidbodys cannot be parented to other rigidbodies. Try it one day and see what happens. The best way to manage rigidbodys that must move together is to use joints.
Edit: Just checked. The new EventSystem, that is designed to replace the OnMouseXXX methods, does not behave this way. You can use the event system by
Adding a physics raycaster to your camera
Creating an EventSystem game object (Create -> UI -> EventSystem)
Adding using UnityEngine.EventSystem to the top of your script
Implementing the IPointerClickHandler interface
Fairly straight forward :)
Answer by pabloj100000 · Feb 28, 2015 at 05:01 PM
Thank you all for the replies. I'm really new to Unity and I have to think about your suggestions and ideas are great. I have to think and read more about them.
I ended up fixing the problem using a ray down from the camera and moving the child gameObjects to a newly defined layer (8 in the code below)
RaycastHit2D hit = Physics2D.GetRayIntersection (Camera.main.ScreenPointToRay(Input.mousePosition), Mathf.Infinity, 1 << 8);
Thanks again Pablo
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Child cant apply variables from parent 2 Answers
Parent class cannot find component 0 Answers
Inheriting Parent Rotation and position 2 Answers
setParent either shrinks my child object or blows it up... What gives? 3 Answers