委托这个对于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); } } }
时间: 2024-10-23 21:09:09