Unity 中 PassEvent 方法优化:仅执行第一个有效按钮回调
Unity 中 PassEvent 方法优化:仅执行第一个有效按钮回调
原始方法:
//把点击事件透下去
public void PassEvent<T>(PointerEventData data, ExecuteEvents.EventFunction<T> function)
where T : IEventSystemHandler
{
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(data, results);
GameObject current = data.pointerCurrentRaycast.gameObject;
var totalFunction = 0;
for (int i = 0; i < results.Count; i++)
{
if (current != results[i].gameObject)
{
ExecuteEvents.Execute(results[i].gameObject, data, function);
}
}
}
问题:
这个方法会执行所有符合条件的按钮的回调函数。如果我们只想执行第一个有效的按钮回调,就需要进行优化。
优化方法:
在执行回调之前添加一个判断条件,当找到第一个有效的按钮后,设置一个标志位来表示已经找到有效按钮并执行了回调,然后在循环中添加判断条件,如果标志位为true则停止循环。
优化后的代码:
//把点击事件透下去
public void PassEvent<T>(PointerEventData data, ExecuteEvents.EventFunction<T> function)
where T : IEventSystemHandler
{
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(data, results);
GameObject current = data.pointerCurrentRaycast.gameObject;
bool foundValidButton = false; // 标志位
for (int i = 0; i < results.Count; i++)
{
if (current != results[i].gameObject)
{
ExecuteEvents.Execute(results[i].gameObject, data, function);
foundValidButton = true; // 执行了有效按钮的回调
break; // 停止循环
}
}
}
解释:
- 添加了一个
foundValidButton标志位,用于判断是否已经找到了有效的按钮并执行了回调。 - 在执行回调函数
ExecuteEvents.Execute之后,将foundValidButton设置为true。 - 在循环中添加判断条件,如果
foundValidButton为true,则停止循环。
注意:
要在执行回调之前设置标志位,以防止在回调中修改标志位导致循环没有停下的情况发生。
改进后的方法可以有效地避免不必要的按钮回调执行,提高代码效率。
原文地址: https://www.cveoy.top/t/topic/qC17 著作权归作者所有。请勿转载和采集!