Unity 关于MVC使用
背景
关于MVC,在某种程度的分离代码逻辑是必要的,可以提高代码的可维护性和重用性。
核心代码:
Model:
using UnityEngine;
using System.Collections;
/// <summary>
/// 模型委托(当用户信息发生变化时执行)
/// </summary>
public delegate void OnValueChange(int val);
public class PlayerMsgModel
{
//玩家等级
private int playerLevel;
//玩家经验
private int playerExperience;
//金币数量
private int goldNum;
//声明委托对象,接收当等级发生变化时,触发的事件
public OnValueChange OnLevelChange;
//声明委托对象,接收当经验发生变化时,触发的事件
public OnValueChange OnExperienceChange;
//声明委托对象,接收当金币数量发生变化时,触发的事件
public OnValueChange OnGoldNumChange;
//单例
private static PlayerMsgModel mod;
public static PlayerMsgModel GetMod()
{
if (mod == null)
{
mod = new PlayerMsgModel();
}
return mod;
}
/// <summary>
/// 玩家等级属性
/// </summary>
/// <value>The player level.</value>
public int PlayerLevel
{
get
{
return playerLevel;
}
set
{
playerLevel = value;
//如果委托对象不为空
if (OnLevelChange != null)
{
//执行委托
OnLevelChange(playerLevel);
}
}
}
/// <summary>
/// 玩家经验属性
/// </summary>
/// <value>The player experience.</value>
public int PlayerExperience
{
get
{
return playerExperience;
}
set
{
playerExperience = value;
if (OnExperienceChange != null)
{
OnExperienceChange(playerExperience);
}
}
}
/// <summary>
/// 金币数量属性
/// </summary>
/// <value>The gold number.</value>
public int GoldNum
{
get
{
return goldNum;
}
set
{
goldNum = value;
if (OnGoldNumChange != null)
{
OnGoldNumChange(goldNum);
}
}
}
}
View:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerMsgView : MonoBehaviour
{
//UI
public Text playerLevel;
public Text playerExperience;
public Text goldNum;
public Button experienceUpButton;
void Start()
{
//委托事件绑定
PlayerMsgModel.GetMod().OnLevelChange += SetLevel;
//委托事件绑定
PlayerMsgModel.GetMod().OnExperienceChange += SetExperience;
PlayerMsgModel.GetMod().OnGoldNumChange += SetGoldNum;
//View绑定按钮控制功能
experienceUpButton.onClick.AddListener(PlayerMsgController.controller.OnExperienceUpButtonClick);
}
//修改UILevel值
public void SetLevel(int level)
{
playerLevel.text = level.ToString();
}
//修改UI经验值
public void SetExperience(int experience)
{
playerExperience.text = experience.ToString();
}
//修改金币
public void SetGoldNum(int goldn)
{
goldNum.text = goldn.ToString();
}
}
Controller:
using UnityEngine;
using System.Collections;
public class PlayerMsgController
{
void Start()
{
PlayerMsgModel.GetMod().PlayerLevel = 1;
PlayerMsgModel.GetMod().PlayerExperience =0;
PlayerMsgModel.GetMod().GoldNum = 0;
}
/// <summary>
/// 提升经验按钮点击事件
/// </summary>
public void OnExperienceUpButtonClick()
{
PlayerMsgModel.GetMod().PlayerExperience += levelUpValue;
PlayerMsgModel.GetMod().PlayerLevel += 1;
PlayerMsgModel.GetMod().GoldNum += 2;
levelUpValue += 20;
}
}
通过简单的Demo可以理解下,Demo_015链接:
链接:https://pan.baidu.com/s/1CP4FLttldNHW-gW2zUrlDA
提取码:ncv6