Unity3D用MVC框架思想实现的小例子

xiaoxiao2021-02-28  19

模型Model脚本(GameModel)

using UnityEngine; using System.Collections; using System.Collections.Generic; //model是双向的,中间的 public class GameModel : MonoBehaviour { //委托model去通知自身view(是用事件完成的),实例---(通知改变) public event UpdateDataEventHandle updateDataEvent; //玩家名称 private string playerName; //玩家经验 private float playerExperience; //玩家等级 private float playerLevel; public string PlayerName { get { return playerName; } set { playerName = value; //当值发生改变的时候直接调用更新(通知改变) updateDataEvent (playerName, playerExperience, playerLevel); } } public float PlayerExperience { get { return playerExperience; } set { playerExperience = value; updateDataEvent (playerName, playerExperience, playerLevel); } } public float PlayerLevel { get { return playerLevel; } set { playerLevel = value; updateDataEvent (playerName, playerExperience, playerLevel); } } }

控制器Controller脚本(GameController)

using UnityEngine; using System.Collections; using System.Collections.Generic; //控制器主要是初始化,以及按钮的事件 public class GameController : MonoBehaviour { public static GameController instance; private GameModel mod; private GameView view; void Awake(){ instance = this; mod = GetComponent<GameModel> ();//绑定model view = GameObject.Find ("Canvas").GetComponent<GameView> ();//绑定View } void Start(){ //mod里的委托事件与view绑定(通知改变事件) mod.updateDataEvent += view.UpdateViewData; ModelInit (); } void ModelInit(){ //附上初始值 mod.PlayerExperience=0; mod.PlayerLevel = 1; mod.PlayerName="frank901"; } /// <summary> /// 按钮事件方法(用户请求) /// </summary> public void OnButtonClick(){ //controller通知model(状态改变) mod.PlayerExperience += 30; if (mod.PlayerExperience >= mod.PlayerLevel * 100) { mod.PlayerExperience -= mod.PlayerLevel * 100; mod.PlayerLevel++; } } }

视图View脚本(GameView)

using UnityEngine; using System.Collections; using UnityEngine.UI; //View主要是UI,监听,中心的显示 public delegate void UpdateDataEventHandle(string name,float experience,float level);//因为是事件(通知改变)所以用到委托 public class GameView : MonoBehaviour { private InputField showBox; private Button addExBtn; void Awake(){ //找到UI对象 showBox = transform.Find ("InputField").GetComponent<InputField> (); addExBtn = transform.Find ("Button").GetComponent<Button> (); } //为了防止出现空引用,依据mono生命周期的执行顺序,所以把调用单例放在Start里 void Start(){ //绑定GameController的回调(用户请求事件) addExBtn.onClick.AddListener(GameController.instance.OnButtonClick); } //更新数据,通知改变(从model到view)是一个事件(通知改变) public void UpdateViewData(string name,float experience,float level){ showBox.text = "Name:" + name + "Experience:" + experience.ToString() + "level:" + level; } }

转载请注明原文地址: https://www.6miu.com/read-1100043.html

最新回复(0)