标签:unity3d培训 unity3d游戏 unity培训 3d游戏开发 unity3d学习
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);
}
}
更多内容,请访问【狗刨学习网】unity极致学院 http://edu.gopedu.com
声明:此篇文档时来自于【狗刨学习网】社区-unity极致学院,是网友自行发布的Unity3D学习文章,如果有什么内容侵犯了你的相关权益,请与官方沟通,我们会即时处理。
在Unity中使用事件/委托机制(event/delegate)进行GameObject之间的通信
标签:unity3d培训 unity3d游戏 unity培训 3d游戏开发 unity3d学习
原文地址:http://blog.csdn.net/book_longssl/article/details/44003195