Unity之一天一个技术点(十九)--初学委托

委托这个对于C#初学者比较头疼,我也是看了半天资料才稍微弄懂一点,下面的代码还是挺简单的,也算用了委托这么逼格高的技术了。


using UnityEngine;
using System.Collections;

//三个军衔级别的命令类型//  
public enum TypeOfCommands
{
    General,
    Captain,
    Soldier
}

public class EventManager : MonoBehaviour
{

    //定义一个通用代理,根据传递类型,发送消息  
    public delegate void CommonUse(TypeOfCommands cmd);
    //定义一个事件发送三个军衔的命定  
    public static event CommonUse whenStep_CommonUse;

    //通用指令传递事件类型//  
    public static void sendMessage_Common(TypeOfCommands toc)
    {
        whenStep_CommonUse(toc);
    }
}


using UnityEngine;
using System.Collections;


public class MainLogic : MonoBehaviour
{

    public GUIText myGuiText;//用于显示消息的ui文字  

  
    void Start()
    {
        EventManager.whenStep_CommonUse += whenStep;
    }
  

    //根据命令类型,执行  
    void whenStep(TypeOfCommands toc)
    {
        switch (toc)
        {
            case TypeOfCommands.General:
                myGuiText.text = "i'm General,the captain should hear from me";
                break;
            case TypeOfCommands.Captain:
                myGuiText.text = "i'm Captain,every soldier need to obey to me";
                break;
            case TypeOfCommands.Soldier:
                myGuiText.text = "i'm soldier,i need to receive commands";
                break;

        }
    }

 
    void OnGUI()  
    {  
        if(GUI.Button(new Rect(0,0,100,30),"General"))  
        {  
            EventManager.sendMessage_Common(TypeOfCommands.General);  
        }  
        if(GUI.Button(new Rect(0,50,100,30),"Captain"))  
        {  
            EventManager.sendMessage_Common(TypeOfCommands.Captain);  
        }  
        if(GUI.Button(new Rect(0,100,100,30),"Soldier"))  
        {  
            EventManager.sendMessage_Common(TypeOfCommands.Soldier);  
        }  
          
    }  

}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值