声明委托
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 + "退出");
}
Unity 碰撞器(Collider)与触发器(Trigger)_unity colider 触发器碰撞触发器-CSDN博客文章浏览阅读1.1w次,点赞7次,收藏26次。要产生碰撞必须为游戏对象添加刚体(Rigidbody)和碰撞器,刚体可以让物体在物理影响下运动。碰撞体是物理组件的一类,它要与刚体一起添加到游戏对象上才能触发碰撞。如果两个刚体相互撞在一起,除非两个对象有碰撞体时物理引擎才会计算碰撞,在物理模拟中,没有碰撞体的刚体会彼此相互穿过。物体发生碰撞的必要条件: 两个物体都必须带有碰撞器(Collider),其中一个物体还必须带有Rigidbod_unity colider 触发器碰撞触发器https://blog.csdn.net/sky1466181491/article/details/76684776