关于Unity下的事件、委托的学习

Unity事件系统详解
本文通过两个Unity脚本示例,详细介绍了如何使用事件来进行组件间的通信。BirdController脚本定义了游戏结束和加分两个事件,而TubeController脚本则订阅这些事件并在特定条件下触发相应的处理方法。

我们来看两个简单的脚本,通过这两个脚本可以很清楚的看到事件是如何工作的

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);
    }

}
现在,通过我的注释很容易看出来事件是如何在两个脚本里进行通信的,简单来说一个脚本声明事件,另一个脚本引用事件名并为事件添加自己脚本的方法即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值