我们来看两个简单的脚本,通过这两个脚本可以很清楚的看到事件是如何工作的
using UnityEngine; using System.Collections; using System; public class BirdController : MonoBehaviour { public event EventHandler GameOver; // 注册两个事件 public event EventHandler ScoreAdd; //当离开Empty Trigger的时候,分发ScoreAdd事件 void OnTriggerExit2D(Collider2D col) { if (col.gameObject.name.Equals("empty")) { if (ScoreAdd != null) ScoreAdd(this, EventArgs.Empty); // 执行加金币事件 } } //当开始碰撞的时候,分发GameOver事件 void OnCollisionEnter2D(Collision2D col) { rigidbody2D.velocity = new Vector2(0, 0); if (GameOver != null) GameOver(this, EventArgs.Empty); // 执行游戏结束事件 this.enabled = false; } }
using UnityEngine; using System.Collections; using System; public class TubeController : MonoBehaviour { // Use this for initialization void Start () { GameObject.Find("bird").GetComponent<BirdController>().GameOver += OnGameOver; // 游戏开始为bird对象的BirdController脚本的 GameOver事件添加OnGameOver方法 } void OnDestroy() { if ( GameObject.Find("bird") ) GameObject.Find("bird").GetComponent<BirdController>().GameOver -= OnGameOver; // 结束时,移除事件 } void OnGameOver(object sender, EventArgs e) { rigidbody2D.velocity = new Vector2(0, 0); } }现在,通过我的注释很容易看出来事件是如何在两个脚本里进行通信的,简单来说一个脚本声明事件,另一个脚本引用事件名并为事件添加自己脚本的方法即可。