1. 程式人生 > >unity中經常用的一種委託代理

unity中經常用的一種委託代理

using UnityEngine;
using System.Collections;


public class EventDispatcher : MonoBehaviour {


// Use this for initialization
public delegate void EventHandlerDelegate(GameObject obj);
//public delegate void EventPressDelegate(GameObject obj,bool state);
public delegate void CollidHandlerDelegate(GameObject obj,Collision collider);
public delegate void ColliderHandler(GameObject obj,Collider collider);

private float TimeLimit = 0.2f;
private float DisLimit = 0.2f;
private Vector3 OldPos;
private float OldTime = 0;

public static EventDispatcher GetDispatcher(GameObject go)
{
EventDispatcher dis = go.GetComponent<EventDispatcher>();
if(dis == null)
{
dis = go.AddComponent<EventDispatcher>();
}
return dis;
}
void Start () {
OldTime = Time.time;
OldPos = Input.mousePosition;
}

// Update is called once per frame
void Update () {

}
public EventHandlerDelegate MouseDown;

void OnMouseDown()
{
if(MouseDown != null)
{
MouseDown(this.gameObject);
}
}

public EventHandlerDelegate MouseUp;
public EventHandlerDelegate DoubleClick;
void OnMouseUp()
{
float currentTime = Time.time;
Vector3 currentpos= Input .mousePosition;


if(currentTime - OldTime <=TimeLimit &&Vector3.Distance( currentpos , OldPos) <= DisLimit)
{
if(DoubleClick != null)
{
DoubleClick(this.gameObject);
}
}else
{
if(MouseUp != null)
{
MouseUp(this.gameObject);
}
}
OldPos = currentpos;
OldTime = currentTime;

}
public EventHandlerDelegate MouseOver;
void OnMouseOver ()
{
if (MouseOver != null)
MouseOver (this.gameObject);
}
public event EventHandlerDelegate MouseEnter;
void OnMouseEnter ()
{
if (MouseEnter != null)
MouseEnter (this.gameObject);
}
public event EventHandlerDelegate MouseExit;
void OnMouseExit ()
{
if (MouseExit != null)
MouseExit (this.gameObject);
}
public event EventHandlerDelegate BecameVisible;
void OnBecameVisible ()
{
if (BecameVisible != null)
BecameVisible (this.gameObject);
}
public event EventHandlerDelegate BecameInvisible;
void OnBecameInvisible ()
{
if (BecameInvisible != null)
BecameInvisible (this.gameObject);
}
public event CollidHandlerDelegate CollisionEnter;
void OnCollisionEnter (Collision c)
{
if (CollisionEnter != null)
CollisionEnter (this.gameObject, c);
}
public event CollidHandlerDelegate CollisionExit;
void OnCollisionExit (Collision c)
{
if (CollisionExit != null)
CollisionExit (this.gameObject, c);
}
public event ColliderHandler TriggerEnter;
void OnTriggerEnter(Collider c)
{
if (TriggerEnter != null)
TriggerEnter (this.gameObject, c);
}
public event ColliderHandler TriggerExit;
void OnTriggerExit(Collider c)
{
if(TriggerExit!=null)
{
TriggerExit(this.gameObject,c);
}
}
}