目标
其实我也不知道是为什么了,老板觉得很多问题不需要程序员也能解决问题,于是希望我们能实现一个通过XMl配置就实现UI界面的部分功能,(ps;凡是能用xml解决的问题就用xml解决)高度模板化。加快项目的进度。
制定XMl规则
- xml中的“controller” 的 name 代表着 预设的的名字和深度:
<controller name="TextView" viewDepth = "20"/>
- xml中的“displayList”代表UI预设所以孩子的集合
- 每个孩子都有最基本的属性,名字,类型,Transform等等
- 每个孩子下都有“childrenComponent”,它代表每个孩子挂载的那些组件,以及每个组件特有的初始参数。
<?xml version="1.0" encoding="utf-8"?>
<component size="600,600" pivot="0.5,0.5" anchor="true" opaque="false">
<controller name="TextView" viewDepth = "20"/>
<displayList>
<children chiidrenName = "Bg" type = "UITexture" goPath="self" rect="0,0,1000,577">
<childrenComponent depth = "1" resPath = "Textures/UIBG/Ditukuang_03.png" m_otherData = "textureType=0" ></childrenComponent>
</children>
<children chiidrenName = "Titlelabel" type = "UILabel" goPath="Bg" rect="-2,257,210,50">
<childrenComponent depth = "3" m_otherData = "text=标题文字|fontSize=22|effectStyle=1"></childrenComponent>
</children>
<children chiidrenName = "bg1" type = "UISprite" goPath="Bg" rect="4,40,880,325">
<childrenComponent depth="3" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Ditukuang_04a|spriteType=1"></childrenComponent>
</children>
<children chiidrenName = "bg2" type = "UISprite" goPath="Bg" rect="1,-190,870,110">
<childrenComponent depth="3" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Ditukuang_01|spriteType=1"></childrenComponent>
</children>
<children chiidrenName = "SceneTexBg" type = "UISprite" goPath="Bg" rect="0,80,826,226">
<childrenComponent depth="5" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Ditukuang_mask3|spriteType=1"></childrenComponent>
</children>
<children chiidrenName = "SceneTex1" type = "UITexture" goPath="self" rect="0,80,815,215">
<childrenComponent depth = "4" resPath = "Textures/BattleScene/scene001_xlzd.jpg" m_otherData = "textureType=0" ></childrenComponent>
</children>
<children chiidrenName = "Closebtn" type = "UISprite" goPath="self" rect="464,237,50,50">
<childrenComponent depth="2" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Anniu_guanbi|spriteType=0"></childrenComponent>
</children>
<children chiidrenName = "MoneyBg" type = "UISprite" goPath="self" rect="-226,-70,375,70">
<childrenComponent depth="3" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Ditukuang_mask3|spriteType=1"></childrenComponent>
</children>
<children chiidrenName = "Money1" type = "UISprite" goPath="MoneyBg" rect="-150,0,37,37">
<childrenComponent depth="5" resPath = "WWW/ItemAtlas/ItemAtlas.prefab" m_otherData = "spriteName=Item_101300|spriteType=0"></childrenComponent>
</children>
<children chiidrenName = "Moneylabel1" type = "UILabel" goPath="MoneyBg/Money1" rect="30,0,37,37">
<childrenComponent depth = "5" m_otherData = "text=0|fontSize=22"></childrenComponent>
</children>
<children chiidrenName = "Money2" type = "UISprite" goPath="MoneyBg" rect="-65,0,37,37">
<childrenComponent depth="5" resPath = "WWW/ItemAtlas/ItemAtlas.prefab" m_otherData = "spriteName=Item_5910023|spriteType=0"></childrenComponent>
</children>
<children chiidrenName = "Moneylabel2" type = "UILabel" goPath="MoneyBg/Money2" rect="30,0,37,37">
<childrenComponent depth = "5" m_otherData = "text=0|fontSize=22"></childrenComponent>
</children>
<children chiidrenName = "Money3" type = "UISprite" goPath="MoneyBg" rect="20,0,37,37">
<childrenComponent depth="5" resPath = "WWW/ItemAtlas/ItemAtlas.prefab" m_otherData = "spriteName=Item_5910025|spriteType=0"></childrenComponent>
</children>
<children chiidrenName = "Moneylabel3" type = "UILabel" goPath="MoneyBg/Money3" rect="30,0,37,37">
<childrenComponent depth = "5" m_otherData = "text=0|fontSize=22"></childrenComponent>
</children>
<children chiidrenName = "Money4" type = "UISprite" goPath="MoneyBg" rect="105,0,37,37">
<childrenComponent depth="5" resPath = "WWW/ItemAtlas/ItemAtlas.prefab" m_otherData = "spriteName=Item_101301|spriteType=0"></childrenComponent>
</children>
<children chiidrenName = "Moneylabel4" type = "UILabel" goPath="MoneyBg/Money4" rect="30,0,37,37">
<childrenComponent depth = "5" m_otherData = "text=0|fontSize=22"></childrenComponent>
</children>
<children chiidrenName = "RankBtn" type = "UIButton" goPath="self" rect="-493,80,64,90">
<childrenComponent depth="3" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Anniu_00_dikuang_03|spriteType=0"></childrenComponent>
<childrenComponent componentType="UILabel" childrenRect="-5,3,32,70" depth = "3" m_otherData = "text=通关榜|fontSize=19|color=0,0,0"></childrenComponent>
</children>
<children chiidrenName = "Awardbtn1" type = "UIButton" goPath="self" rect="35,-70,120,44">
<childrenComponent depth="6" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Anniu_00_dikuang_01|spriteType=0"></childrenComponent>
<childrenComponent componentType="UILabel" childrenRect="-2,2,102,34" depth = "7" m_otherData = "text=领取奖励|fontSize=18"></childrenComponent>
</children>
<children chiidrenName = "Awardbtn2" type = "UIButton" goPath="self" rect="186,-70,120,44">
<childrenComponent depth="6" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Anniu_00_dikuang_01|spriteType=0"></childrenComponent>
<childrenComponent componentType="UILabel" childrenRect="-2,2,102,34" depth = "7" m_otherData = "text=战利品|fontSize=18"></childrenComponent>
</children>
<children chiidrenName = "Settingbtn" type = "UIButton" goPath="self" rect="337,-70,120,44">
<childrenComponent depth="6" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteName=Anniu_00_dikuang_01|spriteType=0"></childrenComponent>
<childrenComponent componentType="UILabel" childrenRect="-2,2,102,34" depth = "7" m_otherData = "text=设置阵容|fontSize=18|color=9,187,135"></childrenComponent>
</children>
<children chiidrenName = "ProgressBar" type = "UIProgressBar" goPath="self" rect="-332,-168,150,50">
<childrenComponent depth="8" resPath = "Atlases/CommonAtlas/CommonAtlas.prefab" m_otherData = "spriteFore=Jindutiao_beibao_02|spriteBack=Jindutiao_shuxing_00|fillDirection=2"></childrenComponent>
</children>
</displayList>
</component>
制定标准的UI Item模板
先制定最基础的Item模板,比如 UIlabel,UIBUtton,UISprite,UIPanel等,我们从xml取出的组件类型后,直接从Resources文件加载出来,并不是去new一个对象,
创建Lua文件 (根据自己的需求)
现在的游戏几乎都会使用lua,我们随便也把lua文件也创建了。
- 在Resources文件下创建CommonText文件夹。
- 在CommonText文件夹创建Lua模板代码
- 创建LuaScripts文件,用来接收创建的Lua文件
- 编写lua模板文本
commonLuaCodeFacade.txt
ClassName = {}
----------------常量定义区----------------
----------------变量定义区----------------
----------------逻辑功能区----------------
function ClassName.Startup()
ServiceInit
RegiestUIText
end
commonLuaCodeMediator.txt
ClassName = {}
----------------常量定义区----------------
----------------变量定义区----------------
local mView = ClassName;
local mIsShow = false;
----------------逻辑功能区----------------
function ClassName.Init()
end
-- 更新UI
function ClassName.UpdateUI()
local vData = CodeName1_Model.GetClientData()
CodeName1_View.UpdateUI(vData)
end
function ClassName.InitSignal()
strInitSignal
end
-----------------C#调用区-----------------
function ClassName.OnCreated(view, args)
ClassName.InitSignal()
end
function ClassName.OnShow(args)
mIsShow = true;
ClassName.Init()
end
function ClassName.OnHide()
mIsShow = false;
end
commonLuaCodeModel.txt
--业务数据储存、管理
ClassName = {}
----------------常量定义区----------------
----------------变量定义区----------------
local clientData = nil
----------------逻辑功能区----------------
-- 请求服务器数据
function ClassName.SetServerData(_data)
if _data == nil then
return
end
clientData = _data
strEvetNotice
end
function ClassName.GetClientData()
return clientData
end
commonLuaCodeService.txt
-- 服务端消息接受和发送
ClassName = {}
----------------常量定义区----------------
----------------逻辑功能区----------------
function ClassName.Init()
end
-- 数据解析
function ClassName.Handle(buffer)
local nAction = buffer:readUShort();
end
commonLuaCodeSignal.txt
--逻辑消息变量定义
ClassName = {}
----------------常量定义区----------------
----------------变量定义区----------------
----------------逻辑功能区----------------
FunctionName
commonLuaCodeView.txt
ClassName = {}
----------------常量定义区----------------
----------------变量定义区----------------
local mView = ClassNameView;
local isInit = true
ClassNameView.mTransform = nil
ClassNameView.mGameObject = nil
ClassNameView.mUILuaViewComponent = nil
constantStr
variableStr
----------------逻辑功能区----------------
-- 组件获取
function ClassName.InitField()
strInitField
end
-- 添加按钮事件
function ClassName.BtnAddListener()
strBtnAddListener
end
-- 关闭界面
function ClassName.BtnCloseClick()
end
strEvetFunction
-----------------C#调用区-----------------
function ClassName.Init(obj)
if obj == nil then
return
end
View = ClassName
View.mGameObject = obj
View.mTransform = View.mGameObject.transform
View.mUILuaViewComponent = View.mTransform:GetComponent("UILuaView")
ClassName.InitField()
ClassName.BtnAddListener()
end
--------------------滑动列表相关-----------------------------
-- 滑动列表绑定
function ClassName.BindTpGroupGrid(tpList)
end
代码编写
UI组件基础类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
public static class UIConst
{
// 从 0 开始
public enum ComponentType
{
Null,
UILabel,
UISprite,
UILuaView,
UITexture,
UIGrid,
TPLuaLogic,
UIButton,
TPGrid,
TPUIGrid,
BoxCollider,
UIProgressBar,
TPLuaFields,
UIScrollView,
TPGameObjectComponent,
TPUIGray,
UISlider,
TPDragSource,
TPDragTarget,
UILanguageSprite,
UIInput,
UIWidget,
UIPanel,
UIToggle,
}
//预设
public class UIPfb
{
public string name; //名字
public int viewDepth; //深度
public UIPfb()
{
}
public UIPfb(string name, int depth)
{
this.name = name;
viewDepth = depth;
}
}
//预设孩子Item
public class ChildrenItem
{
public GameObject goSelf;
public string name; //名字
public string uiType; //组件类型
public GameObject m_Parent; //父级
public string m_goPath = ""; //父级路径
public Vector3 m_localScale = Vector3.one; //大小
public Vector3 m_localPos = Vector3.zero; //位置
public Quaternion m_Quaternion = new Quaternion(0, 0, 0, 0);
public float m_width = -1; //宽度
public float m_height = -1; //高度
//身上挂的组件
public List<UIBasics> listUIBasics = new List<UIBasics>();
public ChildrenItem(string name, string uiType, string m_goPath, string Rect, string m_localScale = null, string m_localPos = null, string m_Quaternion = null)
{
this.name = name;
this.m_goPath = m_goPath;
this.uiType = uiType;
string[] rects = Rect.Split(',');
if (rects.Length != 4)
{
Debug.LogError("Rect 配置信息出错 name = " + name + "Rect " + Rect);
return;
}
float transform_X = float.Parse(rects[0]);
float transform_Y = float.Parse(rects[1]);
this.m_localPos = new Vector3(transform_X, transform_Y, 0);
m_width = float.Parse(rects[2]);
m_height = float.Parse(rects[3]);
if (m_localScale != null)
{
this.m_localScale = XUtil.String2Vector3(m_localScale);
}
if (m_localPos != null)
{
this.m_localPos = XUtil.String2Vector3(m_localScale);
}
if (m_Quaternion != null)
{
string[] quaternion = m_Quaternion.Split(',');
float x, y, z, w;
x = float.Parse(quaternion[0]);
y = float.Parse(quaternion[1]);
z = float.Parse(quaternion[2]);
w = float.Parse(quaternion[3]);
this.m_Quaternion = new Quaternion(x, y, z, w);
}
listUIBasics.Clear();
}
}
//组件基础
public class UIBasics
{
public string childrenRect = null;
public string componentType = null; //组件类型
public UIWidget.Pivot m_pivot = UIWidget.Pivot.Center; //对齐方式
public Color m_color = Color.white; //颜色
public int m_depth = 1; //深度
public string m_resPath = null; //资源路径
public string m_otherData = ""; //其他数据
// Key 类型 vluae =值
public Dictionary<string, string> dicItemData = new Dictionary<string, string>();
public UIBasics(string componentType = null, string childrenRect = null, string pivot = null, string color = null, string depth = null, string resPath = null, string m_otherData = null)
{
if (componentType != null)
{
this.componentType = componentType;
}
if (childrenRect != null)
{
this.childrenRect = childrenRect;
}
if (pivot != null)
{
this.m_pivot = (UIWidget.Pivot)(int.Parse(pivot));
}
if (color != null)
{
string[] rgb = color.Split(',');
float r = float.Parse(rgb[0]);
float g = float.Parse(rgb[1]);
float b = float.Parse(rgb[2]);
this.m_color = new Color(r / 255f, g / 255f, b / 255f);
}
if (depth != null)
{
this.m_depth = int.Parse(depth);
}
if (resPath != null)
{
this.m_resPath = resPath;
}
if (m_otherData != null)
{
this.m_otherData = m_otherData;
SetOtherItemData(m_otherData);
}
}
private void SetOtherItemData(string otherData)
{
if (otherData == null || otherData == "")
{
return;
}
dicItemData.Clear();
string[] strTerm = otherData.Split('|');
List<string> listKey = new List<string>();
List<string> listVuale = new List<string>();
for (int i = 0; i < strTerm.Length; i++)
{
string[] strData = strTerm[i].Split('=');
listKey.Add(strData[0]);
listVuale.Add(strData[1]);
}
for (int i = 0; i < listKey.Count && i < listVuale.Count; i++)
{
dicItemData[listKey[i]] = listVuale[i];
}
}
}
}
XMl解析辅佐类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
public class XmlReaderHelper
{
private XmlDocument xDoc = null;
private XmlNode m_pNode = null;
public void LoadXml(string path)
{
xDoc = new XmlDocument();
xDoc.Load(path);
}
public bool SelectRoot(string strNodeName)
{
m_pNode = xDoc.SelectSingleNode(strNodeName);
if (m_pNode == null)
{
Debug.LogWarning("XmlReaderHelper SelectRoot, XmlNode can not be null. key : " + strNodeName);
return false;
}
return true;
}
/// <summary>
/// 选中第一个名为*的节点;
/// </summary>
public bool SelectHead(string strNodeName)
{
if (m_pNode == null)
{
Debug.LogWarning("XmlReaderHelper SelectHead, XmlNode can not be null.");
return false;
}
return ReplaceNode(m_pNode.SelectSingleNode(strNodeName));
}
/// <summary>
/// 选中下一个名为 Head节点名字的 节点;
/// </summary>
public bool SelectNext()
{
if (m_pNode == null)
{
Debug.LogWarning("XmlReaderHelper SelectNext, XmlNode can not be null.");
return false;
}
return ReplaceNode(m_pNode.NextSibling);
}
/// <summary>
/// 返回上一层节点;
/// </summary>
public bool ReturnParent()
{
if (m_pNode == null)
{
Debug.LogWarning("XmlReaderHelper ReturnParent, XmlNode can not be null.");
return false;
}
return ReplaceNode(m_pNode.ParentNode);
}
/// <summary>
/// Check 并且 替换 pNode;
/// </summary>
private bool ReplaceNode(XmlNode targetNode)
{
if (targetNode == null)
{
return false;
}
m_pNode = targetNode;
return true;
}
/// <summary>
/// 读取节点内容;
/// </summary>
public string ReadNode()
{
if (m_pNode == null)
{
Debug.LogWarning("XmlReaderHelper ReadNode, XmlNode can not be null.");
return null;
}
return m_pNode.InnerText;
}
public string ReadAttribute(string strKey)
{
if (m_pNode == null)
{
Debug.LogWarning("XmlReaderHelper ReadNode, XmlNode can not be null.");
return null;
}
XmlAttributeCollection xac = m_pNode.Attributes;
if (xac.Count <= 0)
{
Debug.LogWarning("XmlReaderHelper ReadNode, XmlAttributeCollection can not be null.");
return null;
}
XmlAttribute xa = xac[strKey];
if (xa == null)
{
Debug.LogWarning("XmlReaderHelper ReadNode, XmlAttribute can not be null. key : " + strKey);
return null;
}
return xa.Value;
}
public void Close()
{
xDoc = null;
m_pNode = null;
}
}
对象添加组件类
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public static class UIAddComponent
{
//给对象添加 UILabel组件
public static void AddUIlabelComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width, float height)
{
UILabel label = go.GetComponent<UILabel>();
if (label == null)
{
label = go.AddComponent<UILabel>();
}
if (uiBasics.childrenRect != null)
{
string[] rects = uiBasics.childrenRect.Split(',');
float transform_X = float.Parse(rects[0]);
float transform_Y = float.Parse(rects[1]);
float transform_X1 = float.Parse(rects[2]);
float transform_Y1 = float.Parse(rects[3]);
go.transform.localPosition = new Vector3(transform_X, transform_Y, 0);
label.width = (int)transform_X1;
label.height = (int)transform_Y1;
}
else
{
label.width = (int)width;
label.height = (int)height;
}
if (uiBasics.m_resPath != null)
{
UIFont font = AssetDatabase.LoadAssetAtPath<UIFont>(UICreate.m_UIRes + uiBasics.m_resPath);
label.bitmapFont = font;
}
if (uiBasics.dicItemData.ContainsKey("fontSize") == true && uiBasics.dicItemData["fontSize"] != null)
{
//字体大小
label.fontSize = int.Parse(uiBasics.dicItemData["fontSize"]);
}
if (uiBasics.dicItemData.ContainsKey("text") && uiBasics.dicItemData["text"] != null)
{
label.text = uiBasics.dicItemData["text"]; // 默认值
}
if (uiBasics.dicItemData.ContainsKey("effectStyle") && uiBasics.dicItemData["effectStyle"] != null)
{
int effect = int.Parse(uiBasics.dicItemData["effectStyle"]); // 默认值
label.effectStyle = (UILabel.Effect)effect;
if (uiBasics.dicItemData.ContainsKey("effectColor") && uiBasics.dicItemData["effectColor"] != null)
{
string effectColor = uiBasics.dicItemData["effectStyle"]; // 默认值
string[] rgb = effectColor.Split(',');
float r = float.Parse(rgb[0]);
float g = float.Parse(rgb[1]);
float b = float.Parse(rgb[2]);
label.effectColor = new Color(r, g, b);
}
}
label.color = uiBasics.m_color;
label.pivot = uiBasics.m_pivot;
label.depth = uiBasics.m_depth;
// label.applyGradient = false;
}
//给对象添加 UISprite 组件
public static void AddUISpriteComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width, float height)
{
UISprite spr = go.GetComponent<UISprite>();
if (spr == null)
{
spr = go.AddComponent<UISprite>();
}
if (uiBasics.childrenRect != null)
{
string[] rects = uiBasics.childrenRect.Split(',');
float transform_X = float.Parse(rects[0]);
float transform_Y = float.Parse(rects[1]);
float transform_X1 = float.Parse(rects[2]);
float transform_Y1 = float.Parse(rects[3]);
go.transform.localPosition = new Vector3(transform_X, transform_Y, 0);
spr.width = (int)transform_X1;
spr.height = (int)transform_Y1;
}
else
{
spr.width = (int)width;
spr.height = (int)height;
}
if (uiBasics.m_resPath != null)
{
UIAtlas uiatlas = AssetDatabase.LoadAssetAtPath<UIAtlas>(UICreate.m_UIRes + uiBasics.m_resPath);
spr.atlas = uiatlas;
}
if (uiBasics.dicItemData.ContainsKey("spriteName") && uiBasics.dicItemData["spriteName"] != null)
{
spr.spriteName = uiBasics.dicItemData["spriteName"];
}
if (uiBasics.dicItemData.ContainsKey("spriteType") && uiBasics.dicItemData["spriteType"] != null)
{
int type = int.Parse(uiBasics.dicItemData["spriteType"]);
spr.type = (UIBasicSprite.Type)type;
}
if (uiBasics.dicItemData.ContainsKey("flip") && uiBasics.dicItemData["flip"] != null)
{
int type = int.Parse(uiBasics.dicItemData["flip"]);
spr.flip = (UIBasicSprite.Flip)type;
}
spr.pivot = uiBasics.m_pivot;
spr.depth = uiBasics.m_depth;
}
//给对象添加 UILuaView 组件
public static void AddUILuaViewComponent(ref GameObject go, int m_depth)
{
UILuaView luaview = go.GetComponent<UILuaView>();
if (luaview == null)
{
luaview = go.AddComponent<UILuaView>();
}
//luaview.isBackground = true;
//luaview.isClearNpc = false;
//luaview.isDelayClose = true;
//luaview.isActiveWhenHide = true;
//luaview.m_IsNeedOpenMovie = false;
//luaview.m_IsNeedCloseMovie = false;
luaview.mLogicDepth = m_depth;
}
//给对象添加 UITexture 组件
public static void AddUITextureComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width, float height)
{
UITexture texture = go.GetComponent<UITexture>();
if (texture == null)
{
texture = go.AddComponent<UITexture>();
}
if (uiBasics.childrenRect != null)
{
string[] rects = uiBasics.childrenRect.Split(',');
float transform_X = float.Parse(rects[0]);
float transform_Y = float.Parse(rects[1]);
float transform_X1 = float.Parse(rects[2]);
float transform_Y1 = float.Parse(rects[3]);
go.transform.localPosition = new Vector3(transform_X, transform_Y, 0);
texture.width = (int)transform_X1;
texture.height = (int)transform_Y1;
}
else
{
texture.width = (int)width;
texture.height = (int)height;
}
texture.depth = uiBasics.m_depth;
if (uiBasics.m_resPath != null)
{
Texture mainTexture = AssetDatabase.LoadAssetAtPath<Texture>(UICreate.m_UIRes + uiBasics.m_resPath);
texture.mainTexture = mainTexture;
}
if (uiBasics.dicItemData.ContainsKey("textureType"))
{
int type = int.Parse(uiBasics.dicItemData["textureType"]);
texture.type = (UIBasicSprite.Type)type;
}
if (uiBasics.dicItemData.ContainsKey("border"))
{
string[] borders = uiBasics.dicItemData["border"].Split(',');
int x = int.Parse(borders[0]);
int y = int.Parse(borders[1]);
int size_x = int.Parse(borders[2]);
int seze_y = int.Parse(borders[3]);
texture.border = new Vector4(x, y, size_x, seze_y);
}
}
//给对象添加 UIGrid 组件
public static void AddUIGridComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
UIGrid uiGrid = go.GetComponent<UIGrid>();
if (uiGrid == null)
{
uiGrid = go.AddComponent<UIGrid>();
}
if (uiBasics.childrenRect != null)
{
string[] rects = uiBasics.childrenRect.Split(',');
float transform_X = float.Parse(rects[0]);
float transform_Y = float.Parse(rects[1]);
go.transform.localPosition = new Vector3(transform_X, transform_Y, 0);
}
if (uiBasics.dicItemData.ContainsKey("arrangement") == true && uiBasics.dicItemData.ContainsKey("arrangement"))
{
int arrangement = int.Parse(uiBasics.dicItemData["arrangement"]);
uiGrid.arrangement = (UIGrid.Arrangement)arrangement;
}
if (uiBasics.dicItemData.ContainsKey("cellWidth") == true && uiBasics.dicItemData.ContainsKey("cellWidth"))
{
int m_width = int.Parse(uiBasics.dicItemData["cellWidth"]);
uiGrid.cellWidth = m_width;
}
if (uiBasics.dicItemData.ContainsKey("cellHeight") == true && uiBasics.dicItemData.ContainsKey("cellHeight"))
{
int m_height = int.Parse(uiBasics.dicItemData["cellHeight"]);
uiGrid.cellHeight = m_height;
}
if (uiBasics.dicItemData.ContainsKey("maxPerLine") == true && uiBasics.dicItemData.ContainsKey("maxPerLine"))
{
uiGrid.maxPerLine = int.Parse(uiBasics.dicItemData["maxPerLine"]);
}
}
//给对象添加 TPLuaLogic 组件
public static void AddTPLuaLogicComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
TPLuaLogic tpLuaLogic = go.GetComponent<TPLuaLogic>();
if (tpLuaLogic == null)
{
tpLuaLogic = go.AddComponent<TPLuaLogic>();
}
tpLuaLogic.luaTableName = uiBasics.dicItemData["luaTableName"];
}
//给对象添加 UIButton 组件
public static void AddUIButtonComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width = -1, float height = -1)
{
BoxCollider box = go.GetComponent<BoxCollider>();
if (box == null)
{
AddBoxColliderComponent(ref go, uiBasics);
}
UIButton btn = go.GetComponent<UIButton>();
if (btn == null)
{
btn = go.AddComponent<UIButton>();
}
UISprite spr = go.GetComponent<UISprite>();
if (spr != null)
{
btn.tweenTarget = spr.gameObject;
spr.width = (int)width;
spr.height = (int)height;
if (uiBasics.dicItemData.ContainsKey("spriteName"))
{
spr.spriteName = uiBasics.dicItemData["spriteName"];
}
spr.depth = uiBasics.m_depth;
}
else
{
GameObject btnGo = go.transform.Find(uiBasics.dicItemData["tweenTarget"]).gameObject;
btn.tweenTarget = btnGo;
}
if (uiBasics.dicItemData.ContainsKey("normalSprite"))
{
btn.normalSprite = uiBasics.dicItemData["normalSprite"];
}
if (uiBasics.dicItemData.ContainsKey("hoverSprite"))
{
btn.hoverSprite = uiBasics.dicItemData["hoverSprite"];
}
if (uiBasics.dicItemData.ContainsKey("pressedSprite"))
{
btn.pressedSprite = uiBasics.dicItemData["pressedSprite"];
}
if (uiBasics.dicItemData.ContainsKey("disabledSprite"))
{
btn.disabledSprite = uiBasics.dicItemData["disabledSprite"];
}
}
//给对象添加 TPGrid 组件
public static void AddTPGridComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
TPGrid tpGrid = go.GetComponent<TPGrid>();
if (tpGrid == null)
{
tpGrid = go.AddComponent<TPGrid>();
}
if (uiBasics.dicItemData.ContainsKey("m_Prefix") == true && uiBasics.dicItemData.ContainsKey("m_Prefix"))
{
tpGrid.m_Prefix = uiBasics.dicItemData["m_Prefix"];
}
if (uiBasics.dicItemData.ContainsKey("m_PrefabId") == true && uiBasics.dicItemData.ContainsKey("m_PrefabId"))
{
tpGrid.m_PrefabId = uint.Parse(uiBasics.dicItemData["m_PrefabId"]);
}
if (uiBasics.m_resPath != null)
{
GameObject PrefabRef = AssetDatabase.LoadAssetAtPath<GameObject>(UICreate.m_UIRes + uiBasics.m_resPath);
tpGrid.m_PrefabRef = PrefabRef;
}
tpGrid.SelectRadio = TPGrid.SelectMode.Single;
}
//给对象添加 TPUIGrid 组件
public static void AddTPUIGridComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
TPUIGrid tpUIGrid = go.GetComponent<TPUIGrid>();
if (tpUIGrid == null)
{
tpUIGrid = go.AddComponent<TPUIGrid>();
}
if (uiBasics.dicItemData.ContainsKey("arrangement") == true && uiBasics.dicItemData.ContainsKey("arrangement"))
{
int arrangement = int.Parse(uiBasics.dicItemData["arrangement"]);
tpUIGrid.arrangement = (UIGrid.Arrangement)arrangement;
}
if (uiBasics.dicItemData.ContainsKey("cellWidth") == true && uiBasics.dicItemData.ContainsKey("cellWidth"))
{
int m_width = int.Parse(uiBasics.dicItemData["cellWidth"]);
tpUIGrid.cellWidth = m_width;
}
if (uiBasics.dicItemData.ContainsKey("cellHeight") == true && uiBasics.dicItemData.ContainsKey("cellHeight"))
{
int m_height = int.Parse(uiBasics.dicItemData["cellHeight"]);
tpUIGrid.cellHeight = m_height;
}
if (uiBasics.dicItemData.ContainsKey("maxPerLine") == true && uiBasics.dicItemData.ContainsKey("maxPerLine"))
{
tpUIGrid.maxPerLine = int.Parse(uiBasics.dicItemData["maxPerLine"]);
}
}
//给对象添加 BoxCollider 组件
public static void AddBoxColliderComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
BoxCollider box = go.GetComponent<BoxCollider>();
if (box == null)
{
box = go.AddComponent<BoxCollider>();
}
// box.center = uiBasics.m_localPos;
// box.size = uiBasics.m_localScale;
}
//给对象添加 UIProgressBar 组件
public static void AddUIProgressBarComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width, float height)
{
UIProgressBar uiProgressBar = go.GetComponent<UIProgressBar>();
if (uiProgressBar == null)
{
uiProgressBar = go.AddComponent<UIProgressBar>();
}
if (uiBasics.dicItemData.ContainsKey("uiBasicst"))
{
int fillDirection = int.Parse(uiBasics.dicItemData["fillDirection"]);
uiProgressBar.fillDirection = (UIProgressBar.FillDirection)fillDirection;
}
UIAtlas uiatlas = null;
if (uiBasics.m_resPath != null)
{
uiatlas = AssetDatabase.LoadAssetAtPath<UIAtlas>(UICreate.m_UIRes + uiBasics.m_resPath);
}
UISprite spriteBack = go.GetComponent<UISprite>();
if (spriteBack != null)
{
spriteBack.atlas = uiatlas;
spriteBack.width = (int)width;
spriteBack.height = (int)height;
if (uiBasics.dicItemData.ContainsKey("spriteBack"))
{
spriteBack.spriteName = uiBasics.dicItemData["spriteBack"];
}
}
UISprite spriteFore = go.transform.Find("Sprite").GetComponent<UISprite>();
if (spriteFore != null)
{
spriteFore.atlas = uiatlas;
spriteFore.width = (int)width;
spriteFore.height = (int)height;
if (uiBasics.dicItemData.ContainsKey("spriteFore"))
{
spriteFore.spriteName = uiBasics.dicItemData["spriteFore"];
}
}
}
//给对象添加 TPLuaFields 组件
public static void AddTPLuaFieldsComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
TPLuaFields tpLuaFields = go.GetComponent<TPLuaFields>();
if (tpLuaFields == null)
{
tpLuaFields = go.AddComponent<TPLuaFields>();
}
}
//给对象添加 UIScrollView 组件
public static void AddUIScrollViewComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width = -1, float height = -1)
{
UIScrollView uiScrollView = go.GetComponent<UIScrollView>();
if (uiScrollView == null)
{
uiScrollView = go.AddComponent<UIScrollView>();
}
UIPanel panel = go.GetComponent<UIPanel>();
if (panel == null)
{
return;
}
panel.depth = uiBasics.m_depth;
panel.sortingOrder = uiBasics.m_depth;
if (uiBasics.dicItemData.ContainsKey("clipRange"))
{
string[] clipRanges = uiBasics.dicItemData["clipRange"].Split(',');
int x = int.Parse(clipRanges[0]);
int y = int.Parse(clipRanges[1]);
int size_x = int.Parse(clipRanges[2]);
int seze_y = int.Parse(clipRanges[3]);
panel.baseClipRegion = new Vector4(x, y, size_x, seze_y);
}
UIScrollView.Movement m_movement = UIScrollView.Movement.Vertical;
if (uiBasics.dicItemData.ContainsKey("movement"))
{
string movement = uiBasics.dicItemData["movement"];
switch (movement)
{
case "Horizontal":
{
m_movement = UIScrollView.Movement.Horizontal;
break;
}
case "Vertical":
{
m_movement = UIScrollView.Movement.Vertical;
break;
}
case "Unrestricted":
{
m_movement = UIScrollView.Movement.Unrestricted;
break;
}
case "Custom":
{
m_movement = UIScrollView.Movement.Custom;
break;
}
}
uiScrollView.movement = m_movement;
}
}
//给对象添加 TPGameObjectComponent 组件
public static void AddTPGameObjectComponentComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
TPGameObjectComponent tpGameObjectComponent = go.GetComponent<TPGameObjectComponent>();
if (tpGameObjectComponent == null)
{
tpGameObjectComponent = go.AddComponent<TPGameObjectComponent>();
}
}
//给对象添加 TPUIGray 组件
public static void AddTPUIGrayComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
TPUIGray tpUIGray = go.GetComponent<TPUIGray>();
if (tpUIGray == null)
{
tpUIGray = go.AddComponent<TPUIGray>();
}
tpUIGray.grayNode = go;
}
//给对象添加 UISlider 组件
public static void AddUISliderComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width = -1, float height = -1)
{
UISlider uiSlider = go.GetComponent<UISlider>();
if (uiSlider == null)
{
uiSlider = go.AddComponent<UISlider>();
}
UIAtlas atlas = null;
if (uiBasics.m_resPath != null)
{
atlas = AssetDatabase.LoadAssetAtPath<UIAtlas>(UICreate.m_UIRes + uiBasics.m_resPath);
}
UISprite sprBackGround = go.GetComponent<UISprite>();
if (sprBackGround != null && atlas != null)
{
sprBackGround.atlas = atlas;
sprBackGround.depth = uiBasics.m_depth;
sprBackGround.width = (int)width;
sprBackGround.height = (int)height;
if (uiBasics.dicItemData.ContainsKey("sprBackGround") && uiBasics.dicItemData["sprBackGround"] != null)
{
sprBackGround.spriteName = uiBasics.dicItemData["sprBackGround"];
}
}
UISprite sprForeGround = go.transform.Find("Sprite").GetComponent<UISprite>();
if (sprForeGround != null && atlas != null)
{
sprForeGround.atlas = atlas;
sprForeGround.depth = uiBasics.m_depth + 1;
sprForeGround.width = (int)width;
sprForeGround.height = (int)height;
if (uiBasics.dicItemData.ContainsKey("sprForeGround") && uiBasics.dicItemData["sprForeGround"] != null)
{
sprForeGround.spriteName = uiBasics.dicItemData["sprForeGround"];
}
}
UILabel labelName = go.transform.Find("LabelName1").GetComponent<UILabel>();
labelName.gameObject.SetActive(false);
if (uiBasics.dicItemData.ContainsKey("LabelName") && uiBasics.dicItemData["LabelName"] != null)
{
labelName.text = uiBasics.dicItemData["LabelName"];
}
}
//给对象添加 TPDragSource 组件
public static void AddTPDragSourceComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
TPDragSource tpDragSource = go.GetComponent<TPDragSource>();
if (tpDragSource == null)
{
tpDragSource = go.AddComponent<TPDragSource>();
}
}
//给对象添加 TPDragTarget 组件
public static void AddTPDragTargetComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
TPDragTarget tpDragTarget = go.GetComponent<TPDragTarget>();
if (tpDragTarget == null)
{
tpDragTarget = go.AddComponent<TPDragTarget>();
}
}
//给对象添加 UILanguageSprite 组件
public static void AddUILanguageSpriteComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width = -1, float height = -1)
{
UILanguageSprite uiLanguageSprite = go.GetComponent<UILanguageSprite>();
if (uiLanguageSprite == null)
{
uiLanguageSprite = go.AddComponent<UILanguageSprite>();
}
if (width > -1)
{
uiLanguageSprite.width = (int)width;
}
if (height > -1)
{
uiLanguageSprite.height = (int)height;
}
}
//给对象添加 UIInput 组件
public static void AddUIInputComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width = -1, float height = -1)
{
UIInput uiInput = go.GetComponent<UIInput>();
if (uiInput == null)
{
uiInput = go.AddComponent<UIInput>();
}
UISprite spr = go.GetComponent<UISprite>();
if (spr == null)
{
return;
}
if (width > -1)
{
spr.width = (int)width;
}
if (height > -1)
{
spr.height = (int)height;
}
}
//给对象添加 UIWidget 组件
public static void AddUIWidgetComponent(ref GameObject go, UIConst.UIBasics uiBasics, float width = -1, float height = -1)
{
UIWidget uiWidget = go.GetComponent<UIWidget>();
if (uiWidget == null)
{
uiWidget = go.AddComponent<UIWidget>();
}
uiWidget.depth = uiBasics.m_depth;
if (width > -1)
{
uiWidget.width = (int)width;
}
if (height > -1)
{
uiWidget.height = (int)height;
}
}
//给对象添加 UIPanel 组件
public static void AddUIPanelComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
UIPanel uiPanel = go.GetComponent<UIPanel>();
if (uiPanel == null)
{
uiPanel = go.AddComponent<UIPanel>();
}
uiPanel.depth = uiBasics.m_depth;
}
//给对象添加 UIToggle 组件
public static void AddUIToggleComponent(ref GameObject go, UIConst.UIBasics uiBasics)
{
UIToggle uiToggle = go.GetComponent<UIToggle>();
if (uiToggle == null)
{
uiToggle = go.AddComponent<UIToggle>();
}
}
}
创建UI类
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using UnityEditor;
using UnityEngine;
public class UICreate : EditorWindow
{
private static string xmlPath = Application.dataPath + "/Resources/XmlConfig"; // xml路径
private static string createUIPath = Application.dataPath + "/TextCreateUIPrefab"; //生成的UI路径
private static string createLuaCodePath = Application.dataPath + "/Resources/LuaScripts/"; //生成的Lua代码路径
private static string commonPfb = "CommonPfb"; //标准模板
public static string m_UIRes = "Assets/[Resources]/UIRes/";
//生成代码
static string commonLuaCodeView = "";
static string commonLuaCodeMediator = "";
static string commonLuaCodeSignal = "";
static string commonLuaCodeModel = "";
static string commonLuaCodeService = "";
static string commonLuaCodeFacade = "";
//模板路径
static string commonLuaCodeViewPath = Application.dataPath + "/Resources/CommonText/commonLuaCodeView.txt";
static string commonLuaCodeMediatorPath = Application.dataPath + "/Resources/CommonText/commonLuaCodeMediator.txt";
static string commonLuaCodeSignalPath = Application.dataPath + "/Resources/CommonText/commonLuaCodeSignal.txt";
static string commonLuaCodeModelPath = Application.dataPath + "/Resources/CommonText/commonLuaCodeModel.txt";
static string commonLuaCodeServicePath = Application.dataPath + "/Resources/CommonText/commonLuaCodeService.txt";
static string commonLuaCodeFacadePath = Application.dataPath + "/Resources/CommonText/commonLuaCodeFacade.txt";
//UI预设的数据
private static Dictionary<UIConst.UIPfb, List<UIConst.ChildrenItem>> dicAllUIPfb = new Dictionary<UIConst.UIPfb, List<UIConst.ChildrenItem>>();
[MenuItem("UICreate/创建UI")]
private static void CreateTestWindows()
{
UnityEngine.Object fileObj = AssetDatabase.LoadMainAssetAtPath("Assets/[Resources]/UIRes/Atlases/ActivitiesAtlas/ActivitiesAtlas.prefab");
UIAtlas atlas = AssetDatabase.LoadAssetAtPath<UIAtlas>("Assets/[Resources]/UIRes/Atlases/ActivitiesAtlas/ActivitiesAtlas.prefab");
UIAtlas atlas0 = fileObj as UIAtlas;
UnityEngine.Debug.LogError("开始创建UI");
GenerateCodeToLua();
// 1 清空缓存数据
dicAllUIPfb.Clear();
// 2 解析Xml文件 dicAllUIPfb 存放所有待创建的UI预设
GetAllXmlData();
// UI创建
CreatePrefabAllObj();
UnityEngine.Debug.LogError("创建UI结束");
AssetDatabase.Refresh(); //unity刷新,只要有资源修改增加刷新项目,
}
private static void CreatePrefabAllObj()
{
if (dicAllUIPfb.Count <= 0)
{
Debug.LogError("Err :没有要创建的UI");
return;
}
foreach (var item in dicAllUIPfb)
{
string path = "Assets/TextCreateUIPrefab/" + item.Key.name + ".prefab";
//根UI
GameObject uiView = Resources.Load(commonPfb + "/View", typeof(GameObject)) as GameObject;
uiView = GameObject.Instantiate(uiView).gameObject;
uiView.name = item.Key.name;
UIAddComponent.AddUILuaViewComponent(ref uiView, item.Key.viewDepth);
//创建子部件
List<UIConst.ChildrenItem> listChildren = item.Value;
if (listChildren == null || listChildren.Count == 0)
{
return;
}
for (int i = 0; i < listChildren.Count; i++)
{
UIConst.ChildrenItem childrenItem = listChildren[i];
CreateChildrenObj(ref uiView, childrenItem);
}
WriteCommonMediatorLua(item.Key.name, listChildren); // 创建 MediatorLua
WriteCommonViewLua(item.Key.name + "View", listChildren); // 创建 ViewLua
WriteCommonFacadeLua(item.Key.name); // 创建 MediatorLua
WriteCommonServiceLua(item.Key.name);
WriteCommonModeLua(item.Key.name);
WriteCommonSignalLua(item.Key.name);
//不要删除
uiView.layer = 8;
PrefabUtility.CreatePrefab(path, uiView);
}
}
//
private static void CreateChildrenObj(ref GameObject uiView, UIConst.ChildrenItem childrenItem)
{
if (uiView == null || childrenItem == null)
{
return;
}
//1 取出要添加的组件类型
GameObject childer = GetAddChildrenComponent(childrenItem.uiType);
GameObject obgj = GameObject.Instantiate(childer).gameObject;
obgj.name = childrenItem.name;
//2 赋值子父层级
if (childrenItem.m_goPath == "self")
{
obgj.transform.parent = uiView.transform;
}
else
{
Transform _parent = uiView.transform.Find(childrenItem.m_goPath);
obgj.transform.parent = _parent;
}
//3 Transform 基本组件
if (childrenItem.m_localPos != null)
{
//childrenItem.m_localPos == null 使用默认值
obgj.transform.localPosition = childrenItem.m_localPos;
}
if (childrenItem.m_localScale != null)
{
//childrenItem.m_localPos == null 使用默认值
obgj.transform.localScale = childrenItem.m_localScale;
}
// 4 身上的组件赋值
List<UIConst.UIBasics> listUIBasics = childrenItem.listUIBasics;
if (listUIBasics == null || listUIBasics.Count == 0)
{
return;
}
for (int i = 0; i < listUIBasics.Count; i++)
{
SetChildrenComponent(ref obgj, childrenItem, listUIBasics[i]);
}
}
// 添加组件
private static void SetChildrenComponent(ref GameObject children, UIConst.ChildrenItem childrenItem, UIConst.UIBasics uiBasics)
{
float m_width = childrenItem.m_width;
float m_height = childrenItem.m_height;
UIConst.ComponentType componentType = GetChildrenComponentType(childrenItem.uiType);
switch (componentType)
{
case UIConst.ComponentType.Null:
{
break;
}
case UIConst.ComponentType.UILabel:
{
UIAddComponent.AddUIlabelComponent(ref children, uiBasics, m_width, m_height);
break;
}
case UIConst.ComponentType.UISprite:
{
UIAddComponent.AddUISpriteComponent(ref children, uiBasics, m_width, m_height);
break;
}
case UIConst.ComponentType.UILuaView:
{
// UIAddComponent.AddUILuaViewComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.UITexture:
{
UIAddComponent.AddUITextureComponent(ref children, uiBasics, m_width, m_height);
break;
}
case UIConst.ComponentType.UIGrid:
{
UIAddComponent.AddUIGridComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.TPLuaLogic:
{
UIAddComponent.AddTPLuaLogicComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.UIButton:
{
if (uiBasics.componentType != null)
{
//孩子组件
UIConst.ComponentType childType = GetChildrenComponentType(uiBasics.componentType);
if (childType == UIConst.ComponentType.UILabel)
{
GameObject label = children.transform.Find("Label").gameObject;
UIAddComponent.AddUIlabelComponent(ref label, uiBasics, m_width, m_height);
}
}
else
{
UIAddComponent.AddUIButtonComponent(ref children, uiBasics, m_width, m_height);
}
break;
}
case UIConst.ComponentType.TPGrid:
{
UIAddComponent.AddTPGridComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.TPUIGrid:
{
UIAddComponent.AddTPUIGridComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.BoxCollider:
{
UIAddComponent.AddBoxColliderComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.UIProgressBar:
{
UIAddComponent.AddUIProgressBarComponent(ref children, uiBasics, m_width, m_height);
break;
}
case UIConst.ComponentType.TPLuaFields:
{
UIAddComponent.AddTPLuaFieldsComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.UIScrollView:
{
UIAddComponent.AddUIScrollViewComponent(ref children, uiBasics, m_width, m_height);
if (uiBasics.componentType != null)
{
//孩子组件
UIConst.ComponentType childType = GetChildrenComponentType(uiBasics.componentType);
if (childType == UIConst.ComponentType.TPUIGrid)
{
//TPUIGrid
GameObject tpUIGrid = children.transform.Find("Grid").gameObject;
UIAddComponent.AddTPUIGridComponent(ref tpUIGrid, uiBasics);
if (uiBasics.childrenRect != null)
{
string[] rects = uiBasics.childrenRect.Split(',');
float transform_X = float.Parse(rects[0]);
float transform_Y = float.Parse(rects[1]);
tpUIGrid.gameObject.transform.localPosition = new Vector3(transform_X, transform_Y, 0);
}
}
if (childType == UIConst.ComponentType.TPGrid)
{
// TPGrid
GameObject grid = children.transform.Find("Grid").gameObject;
UIAddComponent.AddTPGridComponent(ref grid, uiBasics);
}
}
break;
}
case UIConst.ComponentType.TPGameObjectComponent:
{
UIAddComponent.AddTPGameObjectComponentComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.TPUIGray:
{
UIAddComponent.AddTPUIGrayComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.UISlider:
{
UIAddComponent.AddUISliderComponent(ref children, uiBasics, m_width, m_height);
break;
}
case UIConst.ComponentType.TPDragSource:
{
UIAddComponent.AddTPDragSourceComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.TPDragTarget:
{
UIAddComponent.AddTPDragTargetComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.UILanguageSprite:
{
UIAddComponent.AddUILanguageSpriteComponent(ref children, uiBasics, m_width, m_height);
break;
}
case UIConst.ComponentType.UIInput:
{
UIAddComponent.AddUIInputComponent(ref children, uiBasics, m_width, m_height);
break;
}
case UIConst.ComponentType.UIWidget:
{
UIAddComponent.AddUIWidgetComponent(ref children, uiBasics, m_width, m_height);
break;
}
case UIConst.ComponentType.UIPanel:
{
UIAddComponent.AddUIPanelComponent(ref children, uiBasics);
break;
}
case UIConst.ComponentType.UIToggle:
{
UIAddComponent.AddUIToggleComponent(ref children, uiBasics);
break;
}
}
}
// 获取添加组件
private static GameObject GetAddChildrenComponent(string uiType)
{
switch (uiType)
{
case "Null":
{
break;
}
case "UILabel":
{
return Resources.Load(commonPfb + "/UILabel", typeof(GameObject)) as GameObject;
}
case "UISprite":
{
return Resources.Load(commonPfb + "/UISprite", typeof(GameObject)) as GameObject;
}
case "UILuaView":
{
// UIAddComponent.AddUILuaViewComponent(ref children, uiBasics);
break;
}
case "UITexture":
{
return Resources.Load(commonPfb + "/UITexture", typeof(GameObject)) as GameObject;
}
case "UIGrid":
{
return Resources.Load(commonPfb + "/UIGrid", typeof(GameObject)) as GameObject;
}
case "TPLuaLogic":
{
//UIAddComponent.AddTPLuaLogicComponent(ref children, uiBasics);
break;
}
case "UIButton":
{
return Resources.Load(commonPfb + "/UIButton", typeof(GameObject)) as GameObject;
}
case "TPGrid":
{
//return Resources.Load(commonPfb + "/TPGrid", typeof(GameObject)) as GameObject;
break;
}
case "TPUIGrid":
{
return Resources.Load(commonPfb + "/TPGrid", typeof(GameObject)) as GameObject;
}
case "BoxCollider":
{
// UIAddComponent.AddBoxColliderComponent(ref children, uiBasics);
break;
}
case "UIProgressBar":
{
return Resources.Load(commonPfb + "/UIProgressBar", typeof(GameObject)) as GameObject;
}
case "TPLuaFields":
{
//UIAddComponent.AddTPLuaFieldsComponent(ref children, uiBasics);
break;
}
case "UIScrollView":
{
return Resources.Load(commonPfb + "/UIScrollView", typeof(GameObject)) as GameObject;
}
case "TPGameObjectComponent":
{
// UIAddComponent.AddTPGameObjectComponentComponent(ref children, uiBasics);
break;
}
case "TPUIGray":
{
return Resources.Load(commonPfb + "/TPGrid", typeof(GameObject)) as GameObject;
}
case "UISlider":
{
return Resources.Load(commonPfb + "/UISlider", typeof(GameObject)) as GameObject;
}
case "TPDragSource":
{
// UIAddComponent.AddTPDragSourceComponent(ref children, uiBasics);
break;
}
case "TPDragTarget":
{
// UIAddComponent.AddTPDragTargetComponent(ref children, uiBasics);
break;
}
case "UILanguageSprite":
{
return Resources.Load(commonPfb + "/UILanguageSprite", typeof(GameObject)) as GameObject;
}
case "UIInput":
{
return Resources.Load(commonPfb + "/UIInput", typeof(GameObject)) as GameObject;
}
case "UIWidget":
{
return Resources.Load(commonPfb + "/UIWidget", typeof(GameObject)) as GameObject;
}
case "UIPanel":
{
return Resources.Load(commonPfb + "/UIPanel", typeof(GameObject)) as GameObject;
}
case "UIToggle":
{
//UIAddComponent.AddUIToggleComponent(ref children, uiBasics);
break;
}
}
return null;
}
// 获取添加组件类型
private static UIConst.ComponentType GetChildrenComponentType(string uiType)
{
switch (uiType)
{
case "Null":
{
return UIConst.ComponentType.Null;
}
case "UILabel":
{
return UIConst.ComponentType.UILabel;
}
case "UISprite":
{
return UIConst.ComponentType.UISprite;
}
case "UILuaView":
{
return UIConst.ComponentType.UILuaView;
}
case "UITexture":
{
return UIConst.ComponentType.UITexture;
}
case "UIGrid":
{
return UIConst.ComponentType.UIGrid;
}
case "TPLuaLogic":
{
return UIConst.ComponentType.TPLuaLogic;
}
case "UIButton":
{
return UIConst.ComponentType.UIButton;
}
case "TPGrid":
{
return UIConst.ComponentType.TPGrid;
}
case "TPUIGrid":
{
return UIConst.ComponentType.TPUIGrid;
}
case "BoxCollider":
{
return UIConst.ComponentType.BoxCollider;
}
case "UIProgressBar":
{
return UIConst.ComponentType.UIProgressBar;
}
case "TPLuaFields":
{
return UIConst.ComponentType.TPLuaFields;
}
case "UIScrollView":
{
return UIConst.ComponentType.UIScrollView;
}
case "TPGameObjectComponent":
{
return UIConst.ComponentType.TPGameObjectComponent;
}
case "TPUIGray":
{
return UIConst.ComponentType.TPUIGray;
}
case "UISlider":
{
return UIConst.ComponentType.UISlider;
}
case "TPDragSource":
{
return UIConst.ComponentType.TPDragSource;
}
case "TPDragTarget":
{
return UIConst.ComponentType.TPDragTarget;
}
case "UILanguageSprite":
{
return UIConst.ComponentType.UILanguageSprite;
}
case "UIInput":
{
return UIConst.ComponentType.UIInput;
}
case "UIWidget":
{
return UIConst.ComponentType.UIWidget;
}
case "UIPanel":
{
return UIConst.ComponentType.UIPanel;
}
case "UIToggle":
{
return UIConst.ComponentType.UIToggle;
}
}
return UIConst.ComponentType.Null;
}
//删除所有的预设
private static void DeleteAllPfb()
{
}
//获取并解析xml数据
private static void GetAllXmlData()
{
UnityEngine.Debug.LogError("开始解析XML Path = " + xmlPath);
DirectoryInfo folder = new DirectoryInfo(xmlPath);
var files = folder.GetFiles("*.xml");
for (int i = 0; i < files.Length; i++)
{
//Debug.Log(files[i].Name);
ParseXml(files[i].ToString());
}
UnityEngine.Debug.LogError("解析XML结束");
}
// 解析xml数据
public static void ParseXml(string strData)
{
XmlReaderHelper xrh = new XmlReaderHelper();
xrh.LoadXml(strData);
if (!xrh.SelectRoot("component"))
{
Debug.LogError("GuideData Parse, root Node Can Not Be Null.");
return;
}
UIConst.UIPfb pfb = new UIConst.UIPfb();
List<UIConst.ChildrenItem> listChildrenItem = new List<UIConst.ChildrenItem>();
if (xrh.SelectHead("controller"))
{
pfb.name = xrh.ReadAttribute("name");
pfb.viewDepth = int.Parse(xrh.ReadAttribute("viewDepth"));
xrh.ReturnParent();
}
if (xrh.SelectHead("displayList"))
{
if (xrh.SelectHead("children"))
{
while (true) // Condition Item节点
{
string chiidrenName = xrh.ReadAttribute("chiidrenName"); //子部件的Name
string type = xrh.ReadAttribute("type");
string goPath = xrh.ReadAttribute("goPath");
string rect = xrh.ReadAttribute("rect");
string localScale = xrh.ReadAttribute("localScale");
string localPos = xrh.ReadAttribute("localPos");
string quaternion = xrh.ReadAttribute("quaternion");
UIConst.ChildrenItem childrenItem = new UIConst.ChildrenItem(chiidrenName, type, goPath, rect, localScale, localPos, quaternion);
if (xrh.SelectHead("childrenComponent"))
{
while (true) // Condition Item节点
{
string componentType = xrh.ReadAttribute("componentType");
string childrenRect = xrh.ReadAttribute("childrenRect"); //子部件的Name
string pivot = xrh.ReadAttribute("pivot");
string color = xrh.ReadAttribute("color");
string depth = xrh.ReadAttribute("depth");
string resPath = xrh.ReadAttribute("resPath");
string m_otherData = xrh.ReadAttribute("m_otherData");
UIConst.UIBasics uiBasics = new UIConst.UIBasics(componentType, childrenRect, pivot, color, depth, resPath, m_otherData);
childrenItem.listUIBasics.Add(uiBasics);
if (!xrh.SelectNext())
{
xrh.ReturnParent();
break;
}
}
}
listChildrenItem.Add(childrenItem);
if (!xrh.SelectNext())
{
xrh.ReturnParent();
break;
}
}
}
}
dicAllUIPfb[pfb] = listChildrenItem;
}
public static void GenerateCodeToLua()
{
commonLuaCodeView = ReadCommonTxt(commonLuaCodeViewPath);
commonLuaCodeMediator = ReadCommonTxt(commonLuaCodeMediatorPath);
commonLuaCodeSignal = ReadCommonTxt(commonLuaCodeSignalPath);
commonLuaCodeModel = ReadCommonTxt(commonLuaCodeModelPath);
commonLuaCodeService = ReadCommonTxt(commonLuaCodeServicePath);
commonLuaCodeFacade = ReadCommonTxt(commonLuaCodeFacadePath);
}
//写入 Viewlua
public static void WriteCommonViewLua(string className, List<UIConst.ChildrenItem> listBindChildren)
{
//常量定义的部分
string constantStr = "";
for (int i = 0; i < listBindChildren.Count; i++)
{
string str = "local {0} = nil\n";
string str1 = listBindChildren[i].name;
constantStr += string.Format(str, str1);
}
// 变量定义
string variableStr = "";
//获取组件部分
string strInitField = "";
for (int i = 0; i < listBindChildren.Count; i++)
{
//View.vipSprite = View.mTransform:Find("bg/viplev/Sprite").gameObject:GetComponent("UISprite")
string str = " {0} = View.mTransform:Find({1}):GetComponent({2}))\n";
string str1 = listBindChildren[i].name;
string str2 = "";
if (listBindChildren[i].m_goPath == "self")
{
str2 = "\"" + str1 + "\""; //父级路径加自生
}
else
{
str2 = "\"" + listBindChildren[i].m_goPath + "\\" + str1 + "\""; //父级路径加自生
}
string str3 = "\"" + listBindChildren[i].uiType + "\"";
strInitField += string.Format(str, str1, str2, str3);
}
//事件绑定
string strBtnAddListener = "";
string strEvetFunction = "";
for (int i = 0; i < listBindChildren.Count; i++)
{
if (listBindChildren[i].uiType == "UIButton")
{
// UIEventListener.Get(mClose.gameObject).onClick = View.onClickClose
string str = " UIEventListener.Get({0}.gameObject).onClick = View.{1}\n";
string strEvet = "function {0}.{1}()\n\nend\n";
string str1 = "";
string str2 = "";
string strEvet1 = "";
string strEvet2 = "";
str1 = listBindChildren[i].name;
str2 = "OnClick" + listBindChildren[i].name;
strEvet1 = className;
strEvet2 = str2;
strBtnAddListener += string.Format(str, str1, str2);
strEvetFunction += string.Format(strEvet, strEvet1, strEvet2);
}
}
strEvetFunction += string.Format("function {0}.{1}(_data)\n if _data == nil then return end\nend\n", className, "UpdateUI");
//逻辑功能区
commonLuaCodeView = commonLuaCodeView.Replace("ClassName", className); //替换类名
commonLuaCodeView = commonLuaCodeView.Replace("constantStr", constantStr); //常量定义
commonLuaCodeView = commonLuaCodeView.Replace("variableStr", variableStr); //替换变量
commonLuaCodeView = commonLuaCodeView.Replace("strInitField", strInitField); //替换获取
commonLuaCodeView = commonLuaCodeView.Replace("strBtnAddListener", strBtnAddListener); //替换事件绑定
commonLuaCodeView = commonLuaCodeView.Replace("strEvetFunction", strEvetFunction); //替换事件方法
CreateLuaScripts(className, commonLuaCodeView);
}
//写入 Mediator
public static void WriteCommonMediatorLua(string name, List<UIConst.ChildrenItem> listBindChildren)
{
string _className = name + "Mediator";
commonLuaCodeMediator = commonLuaCodeMediator.Replace("ClassName", _className); //替换类名
string strInitSignal = string.Format(" {0}.{1}():AddListener({2}.{3})\n", name + "Signal", name + "UpdateUI", _className, "UpdateUI");
commonLuaCodeMediator = commonLuaCodeMediator.Replace("strInitSignal", strInitSignal);
// string strEvetFunction = string.Format("function {0}.{1}()\n {2}.UpdateUI()\nend\n", _className, "UpdateUI", name + "View");
//commonLuaCodeMediator = commonLuaCodeMediator.Replace("strEvetFunction", strEvetFunction);
commonLuaCodeMediator = commonLuaCodeMediator.Replace("CodeName1_", name);
CreateLuaScripts(_className, commonLuaCodeMediator);
}
public static void WriteCommonFacadeLua(string name)
{
string _className = name + "Facade";
string str = " GameInstance.ui:RegiestUI(LUA_EUIPanel.{0},\"{1}\", EUIAnchor.eCenter)";
string str1 = "e" + name;
string str2 = name + "Mediator";
string regiestUIText = string.Format(str, str1, str2);
string serviceInit = string.Format(" {0}.Init()", name + "Service");
commonLuaCodeFacade = commonLuaCodeFacade.Replace("ClassName", _className); //替换类名
commonLuaCodeFacade = commonLuaCodeFacade.Replace("ServiceInit", serviceInit); //替换类名
commonLuaCodeFacade = commonLuaCodeFacade.Replace("RegiestUIText", regiestUIText); //替换类名
CreateLuaScripts(_className, commonLuaCodeFacade);
}
public static void WriteCommonServiceLua(string name)
{
string _className = name + "Service";
commonLuaCodeService = commonLuaCodeService.Replace("ClassName", _className); //替换类名
CreateLuaScripts(_className, commonLuaCodeService);
}
public static void WriteCommonModeLua(string name)
{
string _className = name + "Model";
commonLuaCodeModel = commonLuaCodeModel.Replace("ClassName", _className); //替换类名
string strEvetNotice = string.Format(" {0}.{1}():Dispatch({2})", name + "Signal", name + "UpdateUI", "{}");
commonLuaCodeModel = commonLuaCodeModel.Replace("strEvetNotice", strEvetNotice);
CreateLuaScripts(_className, commonLuaCodeModel);
}
public static void WriteCommonSignalLua(string name)
{
//function ClassName.FunctionName()
// return GameInstance.signals.GetSignal(GameInstance.signals, "ClassName", "FunctionName");
//end
string _className = name + "Signal";
string str1 = string.Format("{0}.{1}UpdateUI()\n", _className, name);
string str2 = string.Format(" return GameInstance.signals.GetSignal(GameInstance.signals,\"{0}\",\"{1}UpdateUI\")", _className, name);
string FunctionName = string.Format("function {0}{1}\n\nend\n", str1, str2);
commonLuaCodeSignal = commonLuaCodeSignal.Replace("ClassName", _className); //替换类名
commonLuaCodeSignal = commonLuaCodeSignal.Replace("FunctionName", FunctionName);
CreateLuaScripts(_className, commonLuaCodeSignal);
}
// 创建Lua脚本
public static void CreateLuaScripts(string className, string code)
{
// 写文本
string path = createLuaCodePath + className + ".lua";
Debug.LogError("创建脚本 path= " + path);
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(code);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
// 读模板文本
public static string ReadCommonTxt(string m_FileName, string m_Str = "")
{
try
{
string pathSource = m_FileName;
using (FileStream fsSource = new FileStream(pathSource, FileMode.Open, FileAccess.Read))
{
// Read the source file into a byte array.
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
m_Str = UTF8Encoding.Default.GetString(bytes);
//Debug.LogError(m_Str);
return m_Str;
}
}
catch
{
Debug.LogError("读取文本失败");
}
return null;
}
}