- Home /
OnPointerClick in child's script is not triggered when there exists a OnPointerDown in parent's script
Hi, I have learned Unity for a few days, but I'm in trouble with the relationship between child and parent objects.
I have an UI structure in Hierarchy like this:
Canvas' script
public class CanvasEvent : MonoBehaviour, IPointerDownHandler
{
public void OnPointerDown(PointerEventData eventData)
{
print(name);
}
}
Back's script
public class BackEvent : MonoBehaviour, IPointerClickHandler, IPointerDownHandler
{
public void OnPointerClick(PointerEventData eventData)
{
SceneManager.LoadScene("Menu");
}
public void OnPointerDown(PointerEventData eventData)
{
//OnPointerClick does not work without implement this.
}
}
There was not OnPointerDown event in Back's script in the beginning, and I want to load another scene by clicking Back image.
However, it doesn't work when I click it. It just triggered Canvas' OnPointerDown and print the name "Canvas" and nothing else happened.
I found it works if I delete Canvas' OnPointerDown or implement it in Back's script, but I don't know why I have to do this to make it work.
So my question is:
Why can't I trigger Back's click event without implement IOnPointerDownHandler?
Did it inherited parent's event? Or it's event just bubbled up to parent like javascript?
Answer by zx1230516 · Dec 14, 2019 at 12:51 PM
After trying many times, I think here is the most possible answer:
The execution order is OnPointerDown -> OnPointerUp -> OnPointerClick. If an event is not implemented in child's script, it will bubble up until it find a implemented one in parent's script or reach the root and return the pointer behavior to the chlid.
PointerClick event needs a pointer "Down" and a pointer "Up" behavior, but my "Down" behavior has bubbled up to the parent object and has being captured, so even if the "Up" behavior is executed, there is no "Down" behavior can be combined to a click event in child's script.
Based on this guess, the solution is what I asked in the beginning:
1. Implementing an OnPointerDown event in child's script so that it can prevent pointer "Down" behavior from propagating to parent's script.
2. Deleting the OnPointerDown in the parent's script so that the pointer "Down" behavior won't be captured by any other parents' script.
I cant imagine how many hours you saved me with this one. Pretty hard to find answers on specific stuff like that. Thanks alot!
Answer by Miguelfanclub · Mar 29 at 04:39 PM
OnPointerDown and OnPointerClick functions must be implemented (can be empty) to ensure functions to be called.