• 您的位置:首页 > 新闻动态 > Unity3D

    UNITY3D处理碰撞事件的封装类

    2018/9/22      点击:
      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 { };
    }
    }