福感科技有限公司 欢迎您!
联系方式

    地址:北京市平谷区马坊镇金河北街17号院3号楼7层712

    电话:010-89968230

    网站:http://www.fgsense.com

UNITY3D处理碰撞事件的封装类

2024-6-17 19:32:01      点击:
Unity的物理系统,处理碰撞事件,需要自行实现MonoBehaviour中的void OnTriggerEnter(Collider)等方法,MonoBehaviour的生命周期方法,有些不太常用,可能会经常不记得、或者打错名字,调试还不容易找到原因,很不方便。  
我们可以把常用接口封装起来,让需要实现碰撞事件的类,继承已经封装好的类即可。
using System;
using UnityEngine;
[RequireComponent(typeof(Collider))]
public class ColliderListener : MonoBehaviour {
public ActiononTriggerEnter = delegate { };
public ActiononTriggerStay = delegate { };
public ActiononTriggerExit = delegate { };
public ActiononCollisionEnter = delegate { };
public ActiononCollisionStay = delegate { };
public ActiononCollisionExit = delegate { };
private void OnTriggerEnter(Collider other) {
onTriggerEnter(other);
}
private void OnTriggerStay(Collider other) {
onTriggerStay(other);
}
private void OnTriggerExit(Collider other) {
onTriggerExit(other);
}
private void OnCollisionEnter(Collision other) {
onCollisionEnter(other);
}
private void OnCollisionStay(Collision other) {
onCollisionStay(other);
}
private void OnCollisionExit(Collision other) {
onCollisionExit(other);
}
public virtual void Clear() {
onTriggerEnter = delegate { };
onTriggerStay = delegate { };
onTriggerExit = delegate { };
onCollisionEnter = delegate { };
onCollisionStay = delegate { };
onCollisionExit = delegate { };
}
}

Copyright 2019 www.fgsense.com

福感科技有限公司 版权所有 All Rights Reserved

京ICP备20002031号

010-89968230