使用如下代码动态添加EventTrigger:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var trigger = RespondAera.GetComponent<EventTrigger>(); if (trigger == null) trigger = RespondAera.gameObject.AddComponent<EventTrigger>(); //实例化两个事件 var pointerEnter = new EventTrigger.Entry(); pointerEnter.eventID = EventTriggerType.PointerEnter; UnityAction<BaseEventData> pointerEnterAction = new UnityAction<BaseEventData>(OnPointerEnter); pointerEnter.callback.AddListener(pointerEnterAction); var pointerExit = new EventTrigger.Entry(); pointerExit.eventID = EventTriggerType.PointerExit; UnityAction<BaseEventData> pointerExitAction = new UnityAction<BaseEventData>(OnPointerExit); pointerExit.callback.AddListener(pointerExitAction); //添加事件 trigger.triggers.Add(pointerEnter); trigger.triggers.Add(pointerExit); |
会发生子节点的事件不响应的问题,而如果在Inspector添加事件,就没有问题。
官方文档的有行字描述了可能的原因:
NOTE: Attaching this component to a GameObject will make that object intercept ALL events, and no event bubbling will occur from this object!
也就是说,代码添加的这个EventTrigger,和在Inspector中添加的并不完全一样,会阻挡事件冒泡,传递给子结点。
暂时还没有发现怎么解决这个问题,如果有知道的朋友也可以告知下~