using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[]
args)
{
Counter c = new Counter(new Random().Next(10));
//向该事件添加了一个委托函数
c.ThresholdReached += c_ThresholdReached;
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total = threshold)
{
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.Threshold = threshold;
args.TimeReached = DateTime.Now;
OnThresholdReached(args);
}
}
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
EventHandlerThresholdReachedEventArgs handler = ThresholdReached;
if (handler != null)
{
handler(this, e);
}
}
//添加了一个带泛型参数的事件
public event EventHandlerThresholdReachedEventArgs ThresholdReached;
}
public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}
}
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;
}
}
然后在对这个事件感兴趣的GameObject会通过相应的Handler对该事件进行监听,这样就可以进行一对多的GameObject间的通信了。
using UnityEngine;
using System.Collections;
using System;
public class TubeController : MonoBehaviour {
// Use this for initialization
void Start () {
GameObject.Find("bird").GetComponentBirdController().GameOver += OnGameOver;
}
void OnDestroy() {
if ( GameObject.Find("bird") )
GameObject.Find("bird").GetComponentBirdController().GameOver -= OnGameOver;
}
void OnGameOver(object sender, EventArgs e)
{
rigidbody2D.velocity = new Vector2(0, 0);
}
}