先定义
所有的 UI窗口都继承自UIForm 然后继承自UIFormBase 重写一下这几个方法
C#中通过委托调用Lua中的方法
using UnityEngine;
using XLua;
using System;
using UnityEngine.UI;
namespace YouYou
{
//lua组件类型
public enum LuaComType
{
GameObject = 0,
Transform = 1,
Button = 2,
Image = 3,
YouYouImage = 4,
Text = 5,
YouYouText = 6,
RawImage = 7,
InputField = 8,
Scrollbar = 9,
ScrollView = 10,
MultiScroller = 11
}
/// <summary>
/// Lua窗口Form,LuaCallCSharp标记
/// </summary>
[LuaCallCSharp]
public class LuaForm : UIFormBase
{
[CSharpCallLua]
//给lua中传输transfrom
public delegate void OnInitHandler(Transform transform, object userData);
private OnInitHandler onInit;
[CSharpCallLua]
public delegate void OnOpenHandler(object userData);
private OnOpenHandler onOpen;
[CSharpCallLua]
public delegate void OnCloseHandler();
private OnCloseHandler onClose;
[CSharpCallLua]
public delegate void OnBeforDestroyHandler();
private OnBeforDestroyHandler onBeforDestroy;
private LuaTable scriptEnv;
private LuaEnv luaEnv;
[Header("Lua组件数组")]
[SerializeField]
private LuaCom[] m_LuaComs;
public LuaCom[] LuaComs { get { return m_LuaComs; } }
/// <summary>
/// 根据索引获取组件
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public object GetLuaComs(int index)
{
LuaCom com = m_LuaComs[index];
switch (com.Type)
{
case LuaComType.GameObject:
return com.Trans.gameObject;
case LuaComType.Transform:
return com.Trans;
case LuaComType.Button:
return com.Trans.GetComponent<Button>();
case LuaComType.Image:
return com.Trans.GetComponent<Image>();
case LuaComType.YouYouImage:
return com.Trans.GetComponent<YouYouImage>();
case LuaComType.Text:
return com.Trans.GetComponent<Text>();
case LuaComType.YouYouText:
return com.Trans.GetComponent<YouYouText>();
case LuaComType.RawImage:
return com.Trans.GetComponent<RawImage>();
case LuaComType.InputField:
return com.Trans.GetComponent<InputField>();
case LuaComType.Scrollbar:
return com.Trans.GetComponent<Scrollbar>();
case LuaComType.ScrollView:
return com.Trans.GetComponent<ScrollRect>();
case LuaComType.MultiScroller:
return com.Trans.GetComponent<UIMultiScroller>();
}
return com.Trans;
}
protected override void OnInit(object userData)
{
base.OnInit(userData);
luaEnv = LuaManager.luaEnv;//此处要从LuaManager获取 全局只能有一个
if (luaEnv == null) return;
string prefabName = name;
if (prefabName.Contains("(Clone)"))
{
prefabName = prefabName.Split(new string[] { "(Clone)" }, System.StringSplitOptions.RemoveEmptyEntries)[0] + "View";
}
onInit = luaEnv.Global.GetInPath<OnInitHandler>(prefabName + ".OnInit");
onOpen = luaEnv.Global.GetInPath<OnOpenHandler>(prefabName + ".OnOpen");
onClose = luaEnv.Global.GetInPath<OnCloseHandler>(prefabName + ".OnClose");
onBeforDestroy = luaEnv.Global.GetInPath<OnBeforDestroyHandler>(prefabName + ".OnBeforDestroy");
if (onInit != null) onInit(transform, userData);
}
protected override void OnOpen(object userData)
{
base.OnOpen(userData);
if (onOpen != null) onOpen(userData);
}
protected override void OnClose()
{
base.OnClose();
if (onClose != null) onClose();
}
protected override void OnBeforDestroy()
{
base.OnBeforDestroy();
if (onBeforDestroy != null) onBeforDestroy();
onInit = null;
onOpen = null;
onClose = null;
onBeforDestroy = null;
int len = m_LuaComs.Length;
for (int i = 0; i < len; i++)
{
LuaCom com = m_LuaComs[i];
com.Trans = null;
com = null;
}
}
}
/// <summary>
/// Lua组件
/// </summary>
[Serializable]
public class LuaCom
{
/// <summary>
/// 名称
/// </summary>
public string Name;
/// <summary>
/// 类型
/// </summary>
public LuaComType Type;
/// <summary>
/// 变换
/// </summary>
public Transform Trans;
}
}
using UnityEngine;
namespace YouYou
{
public class UIFormBase : MonoBehaviour
{
/// <summary>
/// UI窗口编号
/// </summary>
public int CurrUIFormId
{
get;
private set;
}
/// <summary>
/// UI分组编号
/// </summary>
public byte GroupId
{
get;
private set;
}
/// <summary>
/// 当前画布
/// </summary>
public Canvas CurrCanvas
{
get;
private set;
}
/// <summary>
/// 窗口关闭时间
/// </summary>
public float CloseTime
{
get;
private set;
}
/// <summary>
/// 禁用层级管理
/// </summary>
public bool DisableUILayer
{
get;
private set;
}
/// <summary>
/// 是否锁定(释放)
/// </summary>
public bool IsLock
{
get;
private set;
}
/// <summary>
/// 用户数据
/// </summary>
public object UserData
{
get;
private set;
}
void Awake()
{
CurrCanvas = GetComponent<Canvas>();
}
internal void Init(int uiFormId, byte groupId, bool disableUILayer, bool isLock, object userData)
{
CurrUIFormId = uiFormId;
GroupId = groupId;
DisableUILayer = disableUILayer;
IsLock = isLock;
UserData = userData;
}
void Start()
{
OnInit(UserData);
Open(UserData, true);
}
internal void Open(object userData, bool isFormInit = false)
{
GameEntry.Auido.PlayAydio(ConstDefine.Audio_ButtonClick);
if (!isFormInit)
{
UserData = userData;
}
if (!DisableUILayer)
{
//进行层级管理 增加层级
GameEntry.UI.SetSortingOrder(this, true);
}
OnOpen(UserData);
}
public void Close()
{
GameEntry.UI.CloseUIForm(this);
}
internal void ToClose()
{
GameEntry.Auido.PlayAydio(ConstDefine.Audio_UIClose);
if (!DisableUILayer)
{
//进行层级管理 减少层级
GameEntry.UI.SetSortingOrder(this, false);
}
OnClose();
CloseTime = Time.time;
//UI窗口回池
GameEntry.UI.EnQueue(this);
}
void OnDestroy()
{
OnBeforDestroy();
}
protected virtual void OnInit(object userData) { }
protected virtual void OnOpen(object userData) { }
protected virtual void OnClose() { }
protected virtual void OnBeforDestroy() { }
}
}
UI_TaskView = { };
local this = UI_TaskView;
local txtTaskNameIndex = 0;
local txtTaskDescIndex = 1;
local imgMoneyIndex = 2;
local btnReceiveImgIndex = 3;
function UI_TaskView.OnInit(transform, userData)
this.InitView(transform);
UI_TaskCtrl.OnInit(userData);
end
function UI_TaskView.InitView(transform)
this.LuaForm = transform:GetComponent(typeof(CS.YouYou.LuaForm));
this.txtTaskName = this.LuaForm:GetLuaComs(txtTaskNameIndex);
this.txtTaskDesc = this.LuaForm:GetLuaComs(txtTaskDescIndex);
this.imgMoney = this.LuaForm:GetLuaComs(imgMoneyIndex);
this.btnReceiveImg = this.LuaForm:GetLuaComs(btnReceiveImgIndex);
end
function UI_TaskView.OnOpen(userData)
UI_TaskCtrl.OnOpen(userData);
end
function UI_TaskView.OnClose()
UI_TaskCtrl.OnClose();
end
function UI_TaskView.OnBeforDestroy()
UI_TaskCtrl.OnBeforDestroy();
end
UI_TaskCtrl = {};
local this = UI_TaskCtrl;
function UI_TaskCtrl.OnInit(userData)
print("UI_TaskCtrl.OnInit")
end
function UI_TaskCtrl.OnOpen(userData)
local rows = TaskDBModel.GetList();
for i = 1, #rows do
local entity = rows[i];
print(entity.Id);
print(entity.Name);
end
--local proto = Task_SearchTaskProto.New();
--Task_SearchTaskProto.SendProto(proto);
--local proto = Task_SearchTaskReturnProto.New();
--Task_SearchTaskReturnProto.SendProto(proto);
--print("给服务器发送消息")
end
function UI_TaskCtrl.OnClose()
end
function UI_TaskCtrl.OnBeforDestroy()
end
自送生成脚本部分
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text;
using YouYou;
using System;
/// <summary>
/// 编辑器拓展
/// </summary>
public class Menu
{
#region Settings 宏设置
[MenuItem("悠游工具/宏设置(Settings)")]
public static void Settings()
{
SettingsWindow win = (SettingsWindow)EditorWindow.GetWindow(typeof(SettingsWindow));
win.titleContent = new GUIContent("宏设置");
win.Show();
}
#endregion
#region CreateLuaView 生成LuaView脚本
[MenuItem("悠游工具/生成LuaView脚本(CreateLuaView)")]
public static void CreateLuaView()
{
if (Selection.transforms.Length == 0)
{
Debug.LogError("请选择一个UI界面");
return;
}
Transform trans = Selection.transforms[0];
LuaForm luaForm = trans.GetComponent<LuaForm>();
if (luaForm == null)
{
Debug.LogError("该UI上没有LuaForm脚本");
return;
}
string viewName = trans.gameObject.name;
LuaCom[] luaComs = luaForm.LuaComs;
int len = luaComs.Length;
StringBuilder sbr = new StringBuilder();
sbr.AppendFormat("");
sbr.AppendFormat("{0}View = {{ }};\n", viewName);
sbr.AppendFormat("local this = {0}View;\n", viewName);
sbr.AppendFormat("\n");
for (int i = 0; i < len; i++)
{
LuaCom com = luaComs[i];
sbr.AppendFormat("local {0}Index = {1};\n", com.Name, i);
}
sbr.AppendFormat("\n");
sbr.AppendFormat("function {0}View.OnInit(transform, userData)\n", viewName);
sbr.AppendFormat(" this.InitView(transform);\n");
sbr.AppendFormat(" {0}Ctrl.OnInit(userData);\n", viewName);
sbr.AppendFormat("end\n");
sbr.AppendFormat("\n");
sbr.AppendFormat("function {0}View.InitView(transform)\n", viewName);
sbr.AppendFormat(" this.LuaForm = transform:GetComponent(typeof(CS.YouYou.LuaForm));\n");
for (int i = 0; i < len; i++)
{
LuaCom com = luaComs[i];
sbr.AppendFormat(" this.{0} = this.LuaForm:GetLuaComs({0}Index);\n", com.Name);
}
sbr.AppendFormat("end\n");
sbr.AppendFormat("\n");
sbr.AppendFormat("function {0}View.OnOpen(userData)\n", viewName);
sbr.AppendFormat(" {0}Ctrl.OnOpen(userData);\n", viewName);
sbr.AppendFormat("end\n");
sbr.AppendFormat("\n");
sbr.AppendFormat("function {0}View.OnClose()\n", viewName);
sbr.AppendFormat(" {0}Ctrl.OnClose();\n", viewName);
sbr.AppendFormat("end\n");
sbr.AppendFormat("\n");
sbr.AppendFormat("function {0}View.OnBeforDestroy()\n", viewName);
sbr.AppendFormat(" {0}Ctrl.OnBeforDestroy();\n", viewName);
sbr.AppendFormat("end");
string path = Application.dataPath + "/Download/xLuaLogic/Modules/Temp/" + viewName + "View.bytes";
using (FileStream fs = new FileStream(path, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(sbr.ToString());
}
}
}
#endregion
#region AssetBundleMgr 资源管理
[MenuItem("悠游工具/资源管理/资源包管理(AssetBundleMgr)")]
public static void AssetBundleMgr()
{
AssetBundleWindow win = (AssetBundleWindow)EditorWindow.GetWindow(typeof(AssetBundleWindow));
win.titleContent = new GUIContent("资源包管理");
win.Show();
}
#endregion
#region AssetBundleCopyToStreamingAsstes 初始资源拷贝到StreamingAsstes
[MenuItem("悠游工具/资源管理/初始资源拷贝到StreamingAsstes")]
public static void AssetBundleCopyToStreamingAsstes()
{
string toPath = Application.streamingAssetsPath + "/AssetBundles/";
if (Directory.Exists(toPath))
{
Directory.Delete(toPath, true);
}
Directory.CreateDirectory(toPath);
IOUtil.CopyDirectory(Application.persistentDataPath, toPath);
//重新生成版本文件
//1.先读取persistentDataPath里边的版本文件 这个版本文件里 存放了所有的资源包信息
byte[] buffer = IOUtil.GetFileBuffer(Application.persistentDataPath + "/VersionFile.bytes");
string version = "";
Dictionary<string, AssetBundleInfoEntity> dic = ResourceManager.GetAssetBundleVersionList(buffer, ref version);
Dictionary<string, AssetBundleInfoEntity> newDic = new Dictionary<string, AssetBundleInfoEntity>();
DirectoryInfo directory = new DirectoryInfo(toPath);
//拿到文件夹下所有文件
FileInfo[] arrFiles = directory.GetFiles("*", SearchOption.AllDirectories);
for (int i = 0; i < arrFiles.Length; i++)
{
FileInfo file = arrFiles[i];
string fullName = file.FullName.Replace("\\", "/"); //全名 包含路径扩展名
string name = fullName.Replace(toPath, "").Replace(".assetbundle", "").Replace(".unity3d", "");
if (name.Equals("AssetInfo.json", StringComparison.CurrentCultureIgnoreCase)
|| name.Equals("Windows", StringComparison.CurrentCultureIgnoreCase)
|| name.Equals("Windows.manifest", StringComparison.CurrentCultureIgnoreCase)
|| name.Equals("Android", StringComparison.CurrentCultureIgnoreCase)
|| name.Equals("Android.manifest", StringComparison.CurrentCultureIgnoreCase)
|| name.Equals("iOS", StringComparison.CurrentCultureIgnoreCase)
|| name.Equals("iOS.manifest", StringComparison.CurrentCultureIgnoreCase)
)
{
File.Delete(file.FullName);
continue;
}
AssetBundleInfoEntity entity = null;
dic.TryGetValue(name, out entity);
if (entity != null)
{
newDic[name] = entity;
}
}
StringBuilder sbContent = new StringBuilder();
sbContent.AppendLine(version);
foreach (var item in newDic)
{
AssetBundleInfoEntity entity = item.Value;
string strLine = string.Format("{0}|{1}|{2}|{3}|{4}", entity.AssetBundleName, entity.MD5, entity.Size, entity.IsFirstData ? 1 : 0, entity.IsEncrypt ? 1 : 0);
sbContent.AppendLine(strLine);
}
IOUtil.CreateTextFile(toPath + "VersionFile.txt", sbContent.ToString());
//=======================
MMO_MemoryStream ms = new MMO_MemoryStream();
string str = sbContent.ToString().Trim();
string[] arr = str.Split('\n');
int len = arr.Length;
ms.WriteInt(len);
for (int i = 0; i < len; i++)
{
if (i == 0)
{
ms.WriteUTF8String(arr[i]);
}
else
{
string[] arrInner = arr[i].Split('|');
ms.WriteUTF8String(arrInner[0]);
ms.WriteUTF8String(arrInner[1]);
ms.WriteInt(int.Parse(arrInner[2]));
ms.WriteByte(byte.Parse(arrInner[3]));
ms.WriteByte(byte.Parse(arrInner[4]));
}
}
string filePath = toPath + "/VersionFile.bytes"; //版本文件路径
buffer = ms.ToArray();
buffer = ZlibHelper.CompressBytes(buffer);
FileStream fs = new FileStream(filePath, FileMode.Create);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
AssetDatabase.Refresh();
Debug.Log("初始资源拷贝到StreamingAsstes完毕");
}
#endregion
#region AssetBundleOpenPersistentDataPath 打开persistentDataPath
[MenuItem("悠游工具/资源管理/打开persistentDataPath")]
public static void AssetBundleOpenPersistentDataPath()
{
string output = Application.persistentDataPath;
if (!Directory.Exists(output))
{
Directory.CreateDirectory(output);
}
output = output.Replace("/", "\\");
System.Diagnostics.Process.Start("explorer.exe", output);
}
#endregion
}