Unity下的MVC编程

来源:互联网 发布:撞车 影评 知乎 编辑:程序博客网 时间:2024/06/02 07:31

Unity是基于组件的,做多了代码难免混乱。因此需要有更好的思路。一个思路就是MVC。但是,在Unity下如何使用MVC的思路来编程,没太多思路。前两天看到一个老外的文章,可以借鉴下。

地址:https://www.toptal.com/unity-unity3d/unity-with-mvc-how-to-level-up-your-game-development

例子下载:http://download.csdn.net/detail/wuyt2008/9615891

下面的图显示了老外的思路


老外设计的结构其实是AMVCC

A是application,用来包含整个项目,并调度用哪个control来响应

M是数据

V是视图,只负责作为事件处理的入口

第一个C是控制器,对所有程序逻辑进行处理

第二个C是组件,不同的组件,组成视图、控制器或模型。




这么说,有点不明白,看下脚本,大概就能理解了。


BounceApplication.cs

using UnityEngine;using System.Collections;// 所有类的基类public class BounceElement : MonoBehaviour{// 让整个应用和所有实例便于访问public BounceApplication app { get { return GameObject.FindObjectOfType<BounceApplication> (); }}}public class BounceApplication : MonoBehaviour{// MVC的根实例public BounceModel model;public BounceView view;public BounceController controller;//迭代所有控制器和通知数据public void Notify (string p_event_path, Object p_target, params object[] p_data){BounceController[] controller_list = GetAllControllers ();foreach (BounceController c in controller_list) {c.OnNotification (p_event_path, p_target, p_data);}}// 获取场景中的所有控制器public BounceController[] GetAllControllers (){ BounceController[] arr = { GameObject.FindObjectOfType<BounceController>() };return arr;}}

BounceModel.cs

using UnityEngine;// 包含与应用相关的所有数据public class BounceModel : BounceElement{// 数据public int bounces;public int winCondition;}


BounceController.cs

using UnityEngine;// 控制应用的工作流public class BounceController : BounceElement{// 处理小球碰撞事件public void OnNotification(string p_event_path,Object p_target,params object[] p_data){switch(p_event_path){case BounceNotification.BallHitGround:app.model.bounces++;Debug.Log("Bounce"+app.model.bounces);if(app.model.bounces >= app.model.winCondition){app.view.ball.enabled = false;app.view.ball.GetComponent<Rigidbody>().isKinematic=true; // 停止小球//通知自身或者其他控制器处理事件app.Notify(BounceNotification.GameComplete,this);            }break;case BounceNotification.GameComplete:Debug.Log("Victory!!");break;}}}

BallView.cs

using UnityEngine;// 小球视图public class BallView : BounceElement{void OnCollisionEnter() { app.Notify(BounceNotification.BallHitGround,this);}}


BounceView.cs

using UnityEngine;// 包含与应用相关的所有视图public class BounceView : BounceElement{public BallView ball;}

BounceNotification.cs

// 给予事件静态访问的字符串public class BounceNotification{public const string BallHitGround = "ball.hit.ground";public const string GameComplete  = "game.complete";/* ...  */public const string GameStart     = "game.start";public const string SceneLoad     = "scene.load";/* ... */}

如果用这个思路来做,会清晰很多,但是感觉就是程序的耦合度太高了。

0 0
原创粉丝点击