[Unity]使用StrangeIOC框架设计响应式编程
下载与安装
- 下载地址 GitHub
StrangeIOC特性介绍
Strange框架的目的是为了在混乱的Unity项目代码中,设计支持响应式编程设计模式
Strange框架中提供的特性大部分都是可选性的
使用EventDispatcher
完成事件分发功能
EventDispatcher
是strange框架内的默认分发系统。将会有Signals
信号能够添加到一个分发系统内。
EventDispatcher
的使用步骤
-
创建
EventDispatcher
对象private EventDispatcher dispatcher = new EventDispatcher();
-
添加
Listener
监听对象void Start () { //当遇到分发的事件为'Fire'时,会自动调用CallBack事件 dispatcher.AddListener ("Fire", ((IEvent payload) => { Debug.Log(payload.data); })); }
-
分发
Fire
类型的字符串//UGUI按钮完成点击事件 public void DidClickButton() { dispatcher.Dispatch ("Fire", "点击了按钮"); }
-
删除响应的监听者
Listener
dispatcher.RemoveListener ("Fire", ecb);
完成一个具体的需求
当程序内的一个游戏对象需要通过键盘控制时,我们可以通过如下代码完成功能
-
HHGameController.cs
using UnityEngine; using System.Collections; using strange.extensions.dispatcher.eventdispatcher.impl; using strange.extensions.dispatcher.eventdispatcher.api; public class HelloView : MonoBehaviour { // Use this for initialization //指定物体对象 public HHPlayer Player; //当前事件对象 private Event e; void OnGUI() { e = Event.current; if (e == null) { return; } Player.Dispatcher.Dispatch (e.keyCode); } }
-
HHPlayer.cs
using UnityEngine; using System.Collections; using strange.extensions.dispatcher.eventdispatcher.impl; using strange.extensions.dispatcher.eventdispatcher.api; public class HHPlayer:MonoBehaviour { private EventDispatcher _dispatcher = null; public EventDispatcher Dispatcher{ get{ if (_dispatcher == null) { _dispatcher = new EventDispatcher (); } return _dispatcher; } } void Start() { this.InitDispatcher (); } private void InitDispatcher() { EventCallback vertical_callback = ((IEvent payload) => { Vector3 translate = new Vector3 (); translate.x = 0f; translate.y = 0f; translate.z = Input.GetAxis ("Vertical") * 0.03f; this.transform.Translate (translate); }); EventCallback horizontal_callback = ((IEvent payload) => { Vector3 rotate = new Vector3(); rotate.x = 0f; rotate.y = 1f; rotate.z = 0f; this.transform.Rotate(rotate,Input.GetAxis("Horizontal")); }); this.Dispatcher.AddListener (KeyCode.W, vertical_callback); this.Dispatcher.AddListener (KeyCode.S, vertical_callback); this.Dispatcher.AddListener (KeyCode.A, horizontal_callback); this.Dispatcher.AddListener (KeyCode.D, horizontal_callback); } }
网友评论