tolua 学习笔记 资源加载、数据读取

效果大概就是这样:
运行游戏,点击显示面板按钮,显示另一个面板,并且读取资源显示对应内容。

附上lua代码:

--UITranScript.lua

UITranScript = 
{
    gameObject = "0",
    data = 0,
};
UITranScript.__index = UITranScript

function UITranScript:new(gameObject, data)
    local o = {};
    setmetatable(o,self);
    o.gameObject = gameObject;
    o.data = data;
    return o;
end
--TranScriptInfo.lua

TranScriptInfo = 
{
    id = "0",
    areaName = "0",
    scriptName = "0",
    scriptIcon = "0",
    scriptTable = "0",
    scriptScene = "0"
};
TranScriptInfo.__index = TranScriptInfo

function TranScriptInfo:new(id,areaName,scriptName,scriptIcon,scriptTable,scriptScene)
    local o = {};
    setmetatable(o,self);
    o.id = id;
    o.areaName = areaName;
    o.scriptName = scriptName;
    o.scriptIcon = scriptIcon;
    o.scriptTable = scriptTable;
    o.scriptScene = scriptScene;
    return o;
end
--SelectTranScriptPanel.lua

require "Logic/UITranScript"
require "Common/define"
require "UnityEngine/Vector2"
require "Controller/SelectTranScriptCtrl"

local gameObject;
local transform;

SelectTranScriptPanel = {};
local this = SelectTranScriptPanel;
local SelectTranScriptCtrl=SelectTranScriptCtrl.New();

function SelectTranScriptPanel.Awake(obj)
    this.CreatePanel();
end

function SelectTranScriptPanel.Start(obj)

end

function SelectTranScriptPanel.CreatePanel()
    resMgr:LoadPrefab('selecttranscript',{'_selectTranScriptPanel'},this.OnLoadFinish);
end

function SelectTranScriptPanel.OnLoadFinish(objs)
    local go=GameObject.Instantiate(objs[0]);

    gameObject = go;
    transform = go.transform;   

    local parent=GameObject.Find("Canvas");
    go.transform:SetParent(parent.transform);
    go.transform:GetComponent("RectTransform").anchoredPosition = Vector2.New(0,0);
    go.transform:GetComponent("RectTransform").sizeDelta = Vector2.New(0,0);
    go.transform:GetComponent("RectTransform").localScale = Vector3.New(1,1,1);

    Util.Log("Finish");

    this.InitPanel();

end

function SelectTranScriptPanel.InitPanel()
    --this.btnClose = transform:FindChild("Close").gameObject;
    --此时key默认从1开始递增
    SelectTranScriptPanel.Sprites = 
    {
        UITranScript:new(transform:FindChild("panel/TranScript").gameObject,0),
        UITranScript:new(transform:FindChild("panel/TranScript2").gameObject,0),
        UITranScript:new(transform:FindChild("panel/TranScript3").gameObject,0),
        UITranScript:new(transform:FindChild("panel/TranScript4").gameObject,0),
        UITranScript:new(transform:FindChild("panel/TranScript5").gameObject,0),
        UITranScript:new(transform:FindChild("panel/TranScript6").gameObject,0),
    }

    SelectTranScriptCtrl.OnCreate(gameObject);

end


function SelectTranScriptPanel.OnDestroy()

end
--SelectTranScriptCtrl.lua

local list = require "list" 
require "Logic/TranScriptInfo"
require "Common/define"

TranScriptInfoList = list:new(); --创建一个链表

SelectTranScriptCtrl = {};
local this = SelectTranScriptCtrl;

local gameObject;
local transform;
local luaBehaviour;

function SelectTranScriptCtrl.New()
    return this;
end

function SelectTranScriptCtrl.Awake()

end

function SelectTranScriptCtrl.OnCreate(obj)
    gameObject = obj;
    transform = obj.transform;
    --luaBehaviour = gameObject:GetComponent('LuaBehaviour');
    local close=gameObject.Find("close");
    EventTriggerListener.Get(close).onPointerClick=EventTriggerListener.Get(close).onPointerClick+this.Close;
    --luaBehaviour:AddClick(SelectTranScriptPanel.btnClose, this.Close);--注册关闭按钮事件
    for index,value in ipairs(SelectTranScriptPanel.Sprites) do   
        --luaBehaviour:AddClick(value.gameObject, this.ImageClick); --注册按钮点击事件
        EventTriggerListener.Get(value.gameObject).onPointerClick=EventTriggerListener.Get(value.gameObject).onPointerClick+this.ImageClick;
    end

    resMgr:LoadTextAsset('data', { 'area' }, this.GetInfo);--读入area.txt文件

end

local nowAreaID = 0;
function SelectTranScriptCtrl.GetInfo(objs)
    --这边踩坑踩了不少。。后面发现没在customsetting.cs中添加 
    --_GT(typeof(StringSplitOptions)),这个东西  
    local str = System.String.New(objs[0]:ToString())
    local strArray = str:Split('\r\n',System.StringSplitOptions.RemoveEmptyEntries);--以换行作为分隔符,分割字符串     
    --local strArray = LuaHelper.StringSplit(str,'\r\n');
    for i = 2, strArray.Length - 1 do
        local temp = System.String.New(strArray[i]);
        local strArray2 = temp:Split(',',System.StringSplitOptions.RemoveEmptyEntries);
        --local strArray2 = LuaHelper.StringSplit(temp,',');

        local l = TranScriptInfo:new(strArray2[0],strArray2[1],strArray2[2],strArray2[3],strArray2[4],strArray2[5]);
        TranScriptInfoList:push(l);--添加
        nowAreaID=nowAreaID+1;
        SelectTranScriptCtrl.Refresh(nowAreaID);
    end 

end

local nowImageIndex;
local spriteIndex = 1;
function SelectTranScriptCtrl.Refresh(areaID)
    nowImageIndex = 1;

    local now = nil;  

    for i = 1,TranScriptInfoList.length,1 do  --遍历链表
        now = TranScriptInfoList:next(now);  
        local v = now.value; 

        if(v.id == tostring(areaID)) then
            print(spriteIndex);
            SelectTranScriptPanel.Sprites[spriteIndex].data = v;
            spriteIndex = spriteIndex + 1;
            resMgr:LoadSprite('selecttranscript_asset', { v.scriptIcon }, this.ImageInit);  --加载sprite
        end 
    end  
end


function SelectTranScriptCtrl.ImageInit(objs) --设置sprite
    --print(nowImageIndex);

    local go = SelectTranScriptPanel.Sprites[nowImageIndex].gameObject;
    go:GetComponent("Image").sprite = objs[0]; --要在customsetting.cs中添加 _GT(typeof(Image)),_GT(typeof(Sprite)),
    go.transform:FindChild("Text"):GetComponent('Text').text = SelectTranScriptPanel.Sprites[nowImageIndex].data.scriptName;
    nowImageIndex = nowImageIndex + 1; 
end

function SelectTranScriptCtrl.ImageClick(go)
    print('lua click trigger! from GameObject:'.. go.name);
    for index,value in ipairs(SelectTranScriptPanel.Sprites) do   
        if(value.gameObject == go) then
            local v = value.data;

            if(v ~= nil and v ~= 0) then
                print(v.id..v.areaName..v.scriptName..v.scriptIcon..v.scriptTable..v.scriptScene);
            end
        end
    end
end

function SelectTranScriptCtrl.Open(areaID,SelectTranScriptPanel)
    --nowAreaID = areaID;

    --if(TranScriptInfoList.length > 0) then SelectTranScriptCtrl.Refresh(nowAreaID); end

    --print(nowAreaID.."   "..TranScriptInfoList.length)

    --if gameObject == nil then panelMgr:CreatePanel('SelectTranScript', this.OnCreate); 
    if gameObject == nil then
        SelectTranScriptPanel.Awake(gameObject);
    else gameObject:SetActive(true);
    end
end

function SelectTranScriptCtrl.Close(go)
    gameObject:SetActive(false);
end
--SelectAreaPanel.lua
--这个类先放着。。。

local transform;
local gameObject;

SelectAreaPanel = {};
local this = SelectAreaPanel;

--启动事件--
function SelectAreaPanel.Awake(obj)
    gameObject = obj;
    transform = obj.transform;

    this.InitPanel();
    print("Awake lua--->>"..gameObject.name);
end

--初始化面板--
function SelectAreaPanel.InitPanel()
    this.btn = transform:FindChild("Button").gameObject;
    this.btn2 = transform:FindChild("Button2").gameObject;
    this.img = transform:FindChild("Image").gameObject;
end


function SelectAreaPanel.OnDestroy()
    print("OnDestroy---->>>");
end
--SelectAreaCtrl.lua

require "Controller/SelectTranScriptCtrl"
require "View/SelectAreaPanel"
require "View/SelectTranScriptPanel"

require "UnityEngine/Vector3"
require "3rd/pblua/login_pb"
require "3rd/pbc/protobuf"

local sproto = require "3rd/sproto/sproto"
local core = require "sproto.core"
local print_r = require "3rd/sproto/print_r"

SelectAreaCtrl = {};
local this = SelectAreaCtrl;

local panel;
local prompt;
local transform;
local gameObject;

--构建函数--
function SelectAreaCtrl.New()
    return this;
end

function SelectAreaCtrl.Awake()
    print("SelectAreaCtrl.Awake--->>");
    --panelMgr:CreatePanel('_selectAreaPanel', this.OnCreate);
    resMgr:LoadPrefab("selectarea",{"_selectAreaPanel"},this.OnCreate);
end

--启动事件--
function SelectAreaCtrl.OnCreate(objs)


    gameObject = objs[0];
    transform = objs[0].transform;

    local go=GameObject.Instantiate(objs[0]);   
    parent=GameObject.Find("Canvas");
    go.transform:SetParent(parent.transform);
    go.transform:GetComponent("RectTransform").anchoredPosition = Vector2.New(0,0);
    go.transform:GetComponent("RectTransform").sizeDelta = Vector2.New(0,0);
    go.transform:GetComponent("RectTransform").localScale = Vector3.New(1,1,1);

    --SelectAreaPanel.Awake(objs[0]);
    --prompt = transform:GetComponent('LuaBehaviour');
    --prompt:AddClick(SelectAreaPanel.btn, this.OnClick);
    --prompt:AddClick(SelectAreaPanel.btn2, this.OnClick);
    --resMgr:LoadPrefab('prompt', { 'PromptItem' }, this.InitPanel);

    btn=gameObject.Find("Button")
    Listener=EventTriggerListener.Get(btn);
    Listener.onPointerClick=Listener.onPointerClick+SelectAreaCtrl.OnClick;

    --btn2=gameObject.Find("Button2")
    --Listener=EventTriggerListener.Get(btn2);
    --Listener.onPointerClick=Listener.onPointerClick+SelectAreaCtrl.OnClick;

    img=gameObject.Find("Image")
    Listener = EventTriggerListener.Get(img);
    Listener.onPointerClick = Listener.onPointerClick + SelectAreaCtrl.A;
    Listener.onDrag = Listener.onDrag + SelectAreaCtrl.B;

end

function SelectAreaCtrl.A(g)
    print("点到我了!!!");
end

function SelectAreaCtrl.B(g)
    --uicamera=parent.Find("uiCamera");
    img.transform.position=UnityEngine.Input.mousePosition;

    print("好害羞!!!");
end

--初始化面板--
function SelectAreaCtrl.InitPanel(objs)
    local count = 100; 
    local parent = PromptPanel.gridParent;
    for i = 1, count do
        local go = newObject(objs[0]);
        go.name = 'Item'..tostring(i);
        go.transform:SetParent(parent);
        go.transform.localScale = Vector3.one;
        go.transform.localPosition = Vector3.zero;
        prompt:AddClick(go, this.OnItemClick);

        local label = go.transform:FindChild('Text');
        label:GetComponent('Text').text = tostring(i);
    end
end

--滚动项单击--
function SelectAreaCtrl.OnItemClick(go)
    log(go.name);
end

--单击事件--
function SelectAreaCtrl.OnClick(go) 
    if go == btn then 
        SelectTranScriptCtrl.Open("1",SelectTranScriptPanel);
    end
end

做下两个预设

在LuaFramework/Examples创建文件夹Data,创建area.txt,内容如下:

区域ID,区域名字,副本名字,副本图标,副本所在表,副本场景
id,areaName,scriptName,scriptIcon,scriptTable,scriptScene
1,区域一,格林之森,c1,Data/battle_001,battle
2,区域一,天空之城,c2,Data/battle_002,battle
3,区域一,王之遗迹,c3,Data/battle_003,battle
4,区域二,机械牛,d1,Data/battle_004,battle
5,区域二,雪山,d2,Data/battle_005,battle
6,区域二,天界,d3,Data/battle_006,battle

在ResourceManager.cs添加两个方法:

public void LoadSprite(string abName, string[] assetNames, LuaFunction func)
{
    LoadAsset<Sprite>(abName, assetNames, null, func);
}

public void LoadTextAsset(string abName, string[] assetNames, LuaFunction func)
{
    LoadAsset<TextAsset>(abName, assetNames, null, func);
}

在packager.cs添加需要打成AB包的代码:

AddBuildMap("selectArea" + AppConst.ExtName, "*.prefab", "Assets/LuaFramework/Examples/Builds/SelectArea");
AddBuildMap("selectTranScript" + AppConst.ExtName, "*.prefab", "Assets/LuaFramework/Examples/Builds/SelectTranScript");

AddBuildMap("selectTranScript_asset" + AppConst.ExtName, "*.png", "Assets/LuaFramework/Examples/Textures/SelectTranScript");

AddBuildMap("data" + AppConst.ExtName, "*.txt", "Assets/LuaFramework/Examples/Data");

这边还要提下,切记CustomSetting.cs中添加(其实是为了提醒我自己,整天忘记):

_GT(typeof(Image)),
_GT(typeof(Sprite)),
_GT(typeof(Button)),
_GT(typeof(TextAsset)),
_GT(typeof(StringSplitOptions)),

在GameManager.cs中做这样修改。

大概整个思路是:
* 1 unity启动SelectAreaCtrl.lua,调用Awake函数,创建”_selectAreaPanel”面板,然后注册一些ui按钮事件。
* 2 点击显示面板按钮,调用SelectTranScriptCtrl.Open方法,此方法调用SelectTranScriptPanel.Awake方法,创建_selectTranScriptPanel面板,以及一些数据的初始化。
* 3 SelectTranScriptCtrl.GetInfo 加载area.txt文件内容,并且显示在ui上。

实现内容很简单,可是过程用lua来实现,感觉好乱,不过继续努力吧!!!
最后附上工程下载地址: https://github.com/xiaoxiaosen520/LuaFramework_UGUI.git