委托

[code]csharpcode:

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

[code]csharpcode:

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

}
原文地址:https://www.cnblogs.com/harlan1009/p/4303427.html