您的位置:首页 > 编程语言 > Lua

【Lua 第一篇】 Manager + Data 的定义与应用

2015-08-18 15:24 721 查看
新接触Lua,有些词语用的生硬,请多理解!

定义数据类: 便于存取

-- 引用别的Lua文件 ,下面可以直接调用 比如 functions里的方法 : warn('字符串');
require "Common/functions"
require "System/class"

-- 定义变量
local json = require "cjson"
local util = require "3rd/cjson.util"

--数据类 :herodata--
HeroData = class("HeroData")

HeroData.__index = HeroData;
local this = HeroData
--shuxing
function HeroData:New(data)
this.id = data["id"]
this.name = data["name"]
return this
end


HeroManager。cs
<span style="color:#ff0000;">using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace SimpleFramework.Manager {

public class HeroManager : BehaviourBase {

// Use this for initialization
void Start() {

}

public object[] CallMethod(string func, params object[] args) {
return Util.CallMethod("HeroManager", func, args);
}

public void OnInit( )
{
CallMethod("Init");
}
}
}</span>


定义manager。lua类,数据管理类

-- 引用别的Lua文件 ,下面可以直接调用 比如 functions里的方法 : warn('字符串');
require "Logic/hero/HeroData"
require "Common/functions"
require "System/class"

-- 定义变量
local json = require "cjson"
local util = require "3rd/cjson.util"

--管理器--
HeroManager = {};
local this = HeroManager;

local transform;
local gameObject;

function HeroManager.Awake()
end

function HeroManager.Start()
end

function HeroManager.Init()
local path = Util.DataPath.."json/Hero.json";
local text = util.file_load(path);
LuaHelper.OnJsonCallFunc(text,this.OnJsonCallFunc)-- 读取C#脚本 回调回来OnJsonCallFunc()

end

function HeroManager.OnJsonCallFunc(data)
mTextDatas = {};
local tempdata = json.decode(data);
for i,v in ipairs(tempdata) do
local herodata = HeroData:New(v)
mTextDatas[herodata.id] = herodata
end

warn(mTextDatas[13231].name)
end

function HeroManager.OnDestroy()

end


激活Manager 在BehaviourBase.cs 里

using UnityEngine;
using System.Collections;
using PureMVC.Interfaces;
using SimpleFramework.Manager;

namespace SimpleFramework {

public class BehaviourBase : MonoBehaviour {
private AppFacade m_Facade;
private LuaScriptMgr m_LuaMgr;
private ResourceManager m_ResMgr;
private NetworkManager m_NetMgr;
private MusicManager m_MusicMgr;
private TimerManager m_TimerMgr;
private ThreadManager m_ThreadMgr;
<span style="color:#ff0000;">private HeroManager m_HeroMgr;</span>

protected AppFacade facade {
get {
if (m_Facade == null) {
m_Facade = AppFacade.Instance;
}
return m_Facade;
}
}

protected LuaScriptMgr LuaManager {
get {
if (m_LuaMgr == null) {
m_LuaMgr = facade.GetManager<LuaScriptMgr>(ManagerName.Lua);
}
return m_LuaMgr;
}
set { m_LuaMgr = value; }
}

protected ResourceManager ResManager {
get {
if (m_ResMgr == null) {
m_ResMgr = facade.GetManager<ResourceManager>(ManagerName.Resource);
}
return m_ResMgr;
}
}

protected NetworkManager NetManager {
get {
if (m_NetMgr == null) {
m_NetMgr = facade.GetManager<NetworkManager>(ManagerName.Network);
}
return m_NetMgr;
}
}

protected MusicManager MusicManager {
get {
if (m_MusicMgr == null) {
m_MusicMgr = facade.GetManager<MusicManager>(ManagerName.Music);
}
return m_MusicMgr;
}
}

protected TimerManager TimerManger {
get {
if (m_TimerMgr == null) {
m_TimerMgr = facade.GetManager<TimerManager>(ManagerName.Timer);
}
return m_TimerMgr;
}
}

protected ThreadManager ThreadManager {
get {
if (m_ThreadMgr == null) {
m_ThreadMgr = facade.GetManager<ThreadManager>(ManagerName.Thread);
}
return m_ThreadMgr;
}
}

protected TextManager TextMgr {
get {
if (m_TextMgr == null) {
m_TextMgr = facade.GetManager<TextManager>(ManagerName.Text);
}
return m_TextMgr;
}
}

<span style="color:#ff0000;">protected HeroManager HeroMgr {
get {
if (m_HeroMgr == null) {
m_HeroMgr = facade.GetManager<HeroManager>(ManagerName.Hero);
}
return m_HeroMgr;
}
}</span>
}
}


ManagerName 里创建

using UnityEngine;
using System.Collections;

namespace SimpleFramework {
public class ManagerName {
public const string Lua = "LuaScriptMgr";
public const string Game = "GameManager";
public const string Timer = "TimeManager";
public const string Music = "MusicManager";
public const string Panel = "PanelManager";
public const string Network = "NetworkManager";
public const string Resource = "ResourceManager";
public const string Thread = "ThreadManager";
public const string Text = "TextManager";
<span style="color:#ff0000;">	public const string Hero = "HeroManager";</span>
}
}


BootstrapCommands 在创建

using UnityEngine;
using System.Collections;
using PureMVC.Patterns;
using PureMVC.Interfaces;
using SimpleFramework.Manager;
using SimpleFramework;

/**
* 注册Command ,建立 Command 与Notification 之间的映射
*/
public class BootstrapCommands : SimpleCommand {

/// <summary>
/// 执行启动命令
/// </summary>
/// <param name="notification"></param>
public override void Execute(INotification notification) {
//-----------------关联命令-----------------------
Facade.RegisterCommand(NotiConst.DISPATCH_MESSAGE, typeof(SocketCommand));

//-----------------初始化管理器-----------------------
Facade.AddManager(ManagerName.Lua, new LuaScriptMgr());

Facade.AddManager<PanelManager>(ManagerName.Panel);
Facade.AddManager<MusicManager>(ManagerName.Music);
Facade.AddManager<TimerManager>(ManagerName.Timer);
Facade.AddManager<NetworkManager>(ManagerName.Network);
Facade.AddManager<ResourceManager>(ManagerName.Resource);
Facade.AddManager<ThreadManager>(ManagerName.Thread);
Facade.AddManager<TextManager>(ManagerName.Text);
<span style="color:#ff0000;">Facade.AddManager<HeroManager>(ManagerName.Hero);</span>

Facade.AddManager<GameManager>(ManagerName.Game);
Debug.Log("SimpleFramework StartUp-------->>>>>");
}
}
GameManager。cs 里

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using LuaInterface;
using System.Reflection;
using Junfine.Debuger;
using System.IO;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace SimpleFramework.Manager {
public class GameManager : LuaBehaviour {
public LuaScriptMgr uluaMgr;
private List<string> downloadFiles = new List<string>();

/// <summary>
/// 初始化游戏管理器
/// </summary>
void Awake() {
Init();
}

/// <summary>
/// 初始化
/// </summary>
void Init() {
DontDestroyOnLoad(gameObject);  //防止销毁自己

CheckExtractResource(); //释放资源
Screen.sleepTimeout = SleepTimeout.NeverSleep;
Application.targetFrameRate = AppConst.GameFrameRate;
}

/// <summary>
/// 释放资源
/// </summary>
public void CheckExtractResource() {
bool isExists = Directory.Exists(Util.DataPath) &&
Directory.Exists(Util.DataPath + "lua/") && File.Exists(Util.DataPath + "files.txt");
if (isExists || AppConst.DebugMode) {
StartCoroutine(OnUpdateResource());
return;   //文件已经解压过了,自己可添加检查文件列表逻辑
}
StartCoroutine(OnExtractResource());    //启动释放协成
}

IEnumerator OnExtractResource() {
string dataPath = Util.DataPath;  //数据目录
string resPath = Util.AppContentPath(); //游戏包资源目录

if (Directory.Exists(dataPath)) Directory.Delete(dataPath, true);
Directory.CreateDirectory(dataPath);

string infile = resPath + "files.txt";
string outfile = dataPath + "files.txt";
if (File.Exists(outfile)) File.Delete(outfile);

string message = "正在解包文件:>files.txt";
Debug.Log(infile);
Debug.Log(outfile);
if (Application.platform == RuntimePlatform.Android) {
WWW www = new WWW(infile);
yield return www;

if (www.isDone) {
File.WriteAllBytes(outfile, www.bytes);
}
yield return 0;
} else File.Copy(infile, outfile, true);
yield return new WaitForEndOfFrame();

//释放所有文件到数据目录
string[] files = File.ReadAllLines(outfile);
foreach (var file in files) {
string[] fs = file.Split('|');
infile = resPath + fs[0];  //
outfile = dataPath + fs[0];

message = "正在解包文件:>" + fs[0];
Debug.Log("正在解包文件:>" + infile);
facade.SendNotification(NotiConst.UPDATE_MESSAGE, message);

string dir = Path.GetDirectoryName(outfile);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);

if (Application.platform == RuntimePlatform.Android) {
WWW www = new WWW(infile);
yield return www;

if (www.isDone) {
File.WriteAllBytes(outfile, www.bytes);
}
yield return 0;
} else {
if (File.Exists(outfile)) {
File.Delete(outfile);
}
File.Copy(infile, outfile, true);
}
yield return new WaitForEndOfFrame();
}
message = "解包完成!!!";
facade.SendNotification(NotiConst.UPDATE_MESSAGE, message);
yield return new WaitForSeconds(0.1f);

message = string.Empty;
//释放完成,开始启动更新资源
StartCoroutine(OnUpdateResource());
}

/// <summary>
/// 启动更新下载,这里只是个思路演示,此处可启动线程下载更新
/// </summary>
IEnumerator OnUpdateResource() {
if (!AppConst.UpdateMode) {
OnResourceInited();
yield break;
}
string dataPath = Util.DataPath;  //数据目录
string url = AppConst.WebUrl;
string message = string.Empty;
string random = DateTime.Now.ToString("yyyymmddhhmmss");
string listUrl = url + "files.txt?v=" + random;
Debug.LogWarning("LoadUpdate---->>>" + listUrl);

WWW www = new WWW(listUrl); yield return www;
if (www.error != null) {
OnUpdateFailed(string.Empty);
yield break;
}
if (!Directory.Exists(dataPath)) {
Directory.CreateDirectory(dataPath);
}
File.WriteAllBytes(dataPath + "files.txt", www.bytes);
string filesText = www.text;
string[] files = filesText.Split('\n');

for (int i = 0; i < files.Length; i++) {
if (string.IsNullOrEmpty(files[i])) continue;
string[] keyValue = files[i].Split('|');
string f = keyValue[0];
string localfile = (dataPath + f).Trim();
string path = Path.GetDirectoryName(localfile);
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
string fileUrl = url + f + "?v=" + random;
bool canUpdate = !File.Exists(localfile);
if (!canUpdate) {
string remoteMd5 = keyValue[1].Trim();
string localMd5 = Util.md5file(localfile);
canUpdate = !remoteMd5.Equals(localMd5);
if (canUpdate) File.Delete(localfile);
}
if (canUpdate) {   //本地缺少文件
Debug.Log(fileUrl);
message = "downloading>>" + fileUrl;
facade.SendNotification(NotiConst.UPDATE_MESSAGE, message);
/*
www = new WWW(fileUrl); yield return www;
if (www.error != null) {
OnUpdateFailed(path);   //
yield break;
}
File.WriteAllBytes(localfile, www.bytes);
*/
//这里都是资源文件,用线程下载
BeginDownload(fileUrl, localfile);
while (!(IsDownOK(localfile))) { yield return new WaitForEndOfFrame(); }
}
}
yield return new WaitForEndOfFrame();

message = "更新完成!!";
facade.SendNotification(NotiConst.UPDATE_MESSAGE, message);

OnResourceInited();
}

void OnUpdateFailed(string file) {
string message = "更新失败!>" + file;
facade.SendNotification(NotiConst.UPDATE_MESSAGE, message);
}

/// <summary>
/// 是否下载完成
/// </summary>
bool IsDownOK(string file) {
return downloadFiles.Contains(file);
}

/// <summary>
/// 线程下载
/// </summary>
void BeginDownload(string url, string file) {     //线程下载
object[] param = new object[2] { url, file };

ThreadEvent ev = new ThreadEvent();
ev.Key = NotiConst.UPDATE_DOWNLOAD;
ev.evParams.AddRange(param);
ThreadManager.AddEvent(ev, OnThreadCompleted);   //线程下载
}

/// <summary>
/// 线程完成
/// </summary>
/// <param name="data"></param>
void OnThreadCompleted(NotiData data) {
switch (data.evName) {
case NotiConst.UPDATE_EXTRACT:  //解压一个完成
//
break;
case NotiConst.UPDATE_DOWNLOAD: //下载一个完成
downloadFiles.Add(data.evParam.ToString());
break;
}
}

/// <summary>
/// 资源初始化结束
/// </summary>
public void OnResourceInited() {
LuaManager.Start();
LuaManager.DoFile("Logic/Network");      //加载游戏
LuaManager.DoFile("Logic/GameManager");   //加载网络
LuaManager.DoFile("Logic/TextManager");
<span style="color:#ff0000;">LuaManager.DoFile("Logic/HeroManager");</span>
initialize = true;
TextMgr.OnInit();
<span style="color:#ff0000;">HeroMgr.OnInit();</span>
NetManager.OnInit();    //初始化网络

object[] panels = CallMethod("LuaScriptPanel");
//---------------------Lua面板---------------------------
foreach (object o in panels) {
string name = o.ToString().Trim();
if (string.IsNullOrEmpty(name)) continue;
name += "Panel";    //添加

LuaManager.DoFile("View/" + name);
Debug.LogWarning("LoadLua---->>>>" + name + ".lua");
}
//------------------------------------------------------------
CallMethod("OnInitOK");   //初始化完成
}

void Update() {
if (LuaManager != null && initialize) {
LuaManager.Update();
}
}

void LateUpdate() {
if (LuaManager != null && initialize) {
LuaManager.LateUpate();
}
}

void FixedUpdate() {
if (LuaManager != null && initialize) {
LuaManager.FixedUpdate();
}
}

/// <summary>
/// 析构函数
/// </summary>
void OnDestroy() {
if (NetManager != null) {
NetManager.Unload();
}
if (LuaManager != null) {
LuaManager.Destroy();
LuaManager = null;
}
Debug.Log("~GameManager was destroyed");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: