声明委托
public delegate void MyDelegate(Collider trigger);
C# 委托(Delegate) | 菜鸟教程 (runoob.com)https://www.runoob.com/csharp/csharp-delegate.html
定义委托
public MyDelegate onTriggerEnter;
public MyDelegate onTriggerStay;
public MyDelegate onTriggerExit;
动态挂载
public static Listener Get(GameObject go)
{
Listener listener = go.GetComponent<Listener>();
if (listener == null)
listener = go.AddComponent<Listener>();
return listener;
}
监听
private void OnTriggerEnter(Collider trigger)
{
onTriggerEnter?.Invoke(trigger);
}
private void OnTriggerStay(Collider trigger)
{
onTriggerStay?.Invoke(trigger);
}
private void OnTriggerExit(Collider trigger)
{
onTriggerExit?.Invoke(trigger);
}
示例
GameObject colliderObj;
Listener.Get(colliderObj).onTriggerEnter += OnEnter;
Listener.Get(colliderObj).onTriggerStay += OnStay;
Listener.Get(colliderObj).onTriggerExit += OnExit;
void OnEnter(Collider trigger)
{
Debug.Log("物体" + trigger.name + "进入");
}
void OnStay(Collider trigger)
{
Debug.Log("物体" + trigger.name + "停留");
}
void OnExit(Collider trigger)
{
Debug.Log("物体" + trigger.name + "退出");
}