XLua框架搭建——Unity的Update循环

unity的生命周期中有一个Update函数,是游戏的循环,类似的还有FixedUpdate和LateUpdate等,在c#中继承monobehaviour后unity就会调用对应的函数,根据我们前面的设计《XLua框架搭建——LuaBehaviour设计》,我们也可以获取对应的update函数,然后进行调用,但是在lua中是mgr类的非生命周期下的类呢?

无论是c#还是lua都会有这个问题,对于非monobehaviour的类,是没有对应的生命周期函数调用的,想想在c#中的做法,一般是定义一个c#类,继承monobehaviour,然后标记为DontDestroyOnLoad,在类里面添加一些类似于addUpdateListener的方法进行注册,将这些注册放到列表里,在对应的函数里遍历调用对应的注册函数。

在lua中沿用这种方法,我们将刚才写的类加入到导出列表,在lua中新建一个类,在类构造函数中向刚才的c#类注册对应的update回调函数,利用同样的原理,添加AddUpdateListener,AddFixedUpdateListener,AddLateUpdateListener,以及对应的Remove函数,和前面的消息分发一样,在add时需要将self实例一起传过来,然后在刚才注册的回调里遍历列表,进行调用。

代码比较简单,仅供参考

GameUpdate = newClass("GameUpdate", nil)

local m_updateList = {};
local m_fixedUpdateList = {};
local m_lateUpdateList = {};

function GameUpdate.AddUpdate(ins, func)
    local add = {};
    add.ins = ins;
    add.func = func;
    table.insert(m_updateList, add);
end
function GameUpdate.RemoveUpdate( ins, func)
    for i, v in pairs(m_updateList) do
        if v.ins == ins and v.func == func then
            table.remove(m_updateList, i);
        end
    end
end

function GameUpdate.AddFixedUpdate(ins, func)
    local add = {};
    add.ins = ins;
    add.func = func;
    table.insert(m_fixedUpdateList, add);
end
function GameUpdate.RemoveFixedUpdate( ins, func)
    for i, v in pairs(m_fixedUpdateList) do
        if v.ins == ins and v.func == func then
            table.remove(m_fixedUpdateList, i);
        end
    end
end

function GameUpdate.AddLateUpdate(ins, func)
    local add = {};
    add.ins = ins;
    add.func = func;
    table.insert(m_lateUpdateList, add);
end
function GameUpdate.RemoveLateUpdate( ins, func)
    for i, v in pairs(m_lateUpdateList) do
        if v.ins == ins and v.func == func then
            table.remove(m_lateUpdateList, i);
        end
    end
end

function GameUpdate.Update()
    local deltaTime = CS.UnityEngine.Time.deltaTime;
    for i, v in pairs(m_updateList) do
        if v.ins ~= nil then
            v.func(v.ins,deltaTime);
        else
            v.func(deltaTime);
        end
    end
end

function GameUpdate.FixedUpdate()
    local fixedDeltaTime = CS.UnityEngine.Time.fixedDeltaTime;
    for i, v in pairs(m_fixedUpdateList) do
        if v.ins ~= nil then
            v.func(v.ins,fixedDeltaTime);
        else
            v.func(fixedDeltaTime);
        end
    end
end

function GameUpdate:LateUpdate()
    local deltaTime = CS.UnityEngine.Time.deltaTime;
    for i, v in pairs(m_lateUpdateList) do
        if v.ins ~= nil then
            v.func(v.ins,deltaTime);
        else
            v.func(deltaTime);
        end
    end
end

GameUpdate.Instance = GameUpdate.New();

猜你喜欢

转载自blog.csdn.net/suifcd/article/details/79996405
今日推荐