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 ();
}
}
}
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() };
return arr;
}
}
using UnityEngine;
// 包含与应用相关的所有数据
public class BounceModel : BounceElement
{
// 数据
public int bounces;
public int winCondition;
}
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().isKinematic=true; // 停止小球
//通知自身或者其他控制器处理事件
app.Notify(BounceNotification.GameComplete,this);
}
break;
case BounceNotification.GameComplete:
Debug.Log("Victory!!");
break;
}
}
}
using UnityEngine;
// 小球视图
public class BallView : BounceElement
{
void OnCollisionEnter() {
app.Notify(BounceNotification.BallHitGround,this);
}
}
using UnityEngine;
// 包含与应用相关的所有视图
public class BounceView : BounceElement
{
public BallView ball;
}
// 给予事件静态访问的字符串
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";
/* ... */
}