Unity根據XMl配置一鍵生成UI預設

目標

其實我也不知道是爲什麼了,老闆覺得很多問題不需要程序員也能解決問題,於是希望我們能實現一個通過XMl配置就實現UI界面的部分功能,(ps;凡是能用xml解決的問題就用xml解決)高度模板化。加快項目的進度。

制定XMl規則

  1. xml中的“controller” 的 name 代表着 預設的的名字和深度:<controller name="TextView" viewDepth = "20"/>
  2. xml中的“displayList”代表UI預設所以孩子的集合
  3. 每個孩子都有最基本的屬性,名字,類型,Transform等等
  4. 每個孩子下都有“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文件也創建了。

  1. 在Resources文件下創建CommonText文件夾。
  2. 在CommonText文件夾創建Lua模板代碼
  3. 創建LuaScripts文件,用來接收創建的Lua文件
  4. 編寫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;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章