UNITY3D處理碰撞事件的封裝類
2018/9/22??????點(diǎn)擊:
Unity的物理系統(tǒng),處理碰撞事件,需要自行實(shí)現(xiàn)MonoBehaviour中的void OnTriggerEnter(Collider)等方法,MonoBehaviour的生命周期方法,有些不太常用,可能會經(jīng)常不記得、或者打錯(cuò)名字,調(diào)試還不容易找到原因,很不方便。
我們可以把常用接口封裝起來,讓需要實(shí)現(xiàn)碰撞事件的類,繼承已經(jīng)封裝好的類即可。
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 { };
}
}
我們可以把常用接口封裝起來,讓需要實(shí)現(xiàn)碰撞事件的類,繼承已經(jīng)封裝好的類即可。
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 { };
}
}
- 上一篇:Unity3D使用BVH動作文件驅(qū)動模型 2018/9/25
- 下一篇:Unity3D引用dll打包發(fā)布的問題及解決 2018/9/12