1、事件处理
using UnityEngine;
using System.Collections;
using System;
/// <summary>
/// 通常会使用EventHandler来处理接收的事件。使用这种委托模式你必须将事件发送者和EventArgs(或子类)一起传递进来
/// </summary>
public class InfoEventArgs<T> : EventArgs{
public T info;
public InfoEventArgs(){
info = default(T);
}
public InfoEventArgs(T info){
this.info = info;
}
}
2、控制器
using UnityEngine;
using System.Collections;
using System;
public class Point
{
public int x = 0;
public int y = 0;
public Point(int x,int y){
this.x = x;
this.y = y;
}
}
public class InputController : MonoBehaviour
{
public class Repeater
{
const float threshold = 0.5f;
const float rate = 0.25f;
float _next;
bool _hold;
string _axis;
public Repeater (string axisName)
{
_axis = axisName;
}
public int Update ()
{
int retValue = 0;
int value = Mathf.RoundToInt (Input.GetAxisRaw (_axis));
if (value != 0) {
if (Time.time > _next) {
retValue = value;
_next = Time.time + (_hold ? rate : threshold);
_hold = true;
}
} else {
_hold = false;
_next = 0;
}
return retValue;
}
}
Repeater _hor = new Repeater ("Horizontal");
Repeater _ver = new Repeater ("Vertical");
public static event EventHandler<InfoEventArgs<Point>> moveEvent;
public static event EventHandler<InfoEventArgs<int>> fireEvent;
string[] _buttons = new string[] {"Fire1", "Fire2", "Fire3"};
void Update ()
{
// Debug.Log (Input.GetAxis("Horizontal"));
// Debug.Log (Input.GetAxisRaw("Horizontal"));
int x = _hor.Update ();
int y = _ver.Update ();
if (x != 0 || y != 0) {
if (moveEvent != null)
moveEvent (this, new InfoEventArgs<Point> (new Point (x, y)));
}
for (int i = 0; i < 3; ++i)
{
if (Input.GetButtonDown(_buttons[i]))
{
if (fireEvent != null)
fireEvent(this, new InfoEventArgs<int>(i));
}
}
}
}
3、Demo
using UnityEngine;
using System.Collections;
public class Demo : MonoBehaviour {
void OnEnable(){
InputController.moveEvent += OnMoveEvent;
InputController.fireEvent += OnFireEvent;
}
void OnDisable(){
InputController.moveEvent -= OnMoveEvent;
InputController.fireEvent -= OnFireEvent;
}
void OnMoveEvent(object sender, InfoEventArgs<Point> e){
// Debug.Log("Move " + e.info.ToString());
Debug.Log("Move " + e.info.x);
Debug.Log("Move " + e.info.y);
}
void OnFireEvent(object sender, InfoEventArgs<int> e){
Debug.Log("Fire " + e.info.ToString());
}
}