unityとxluaの第3歩はどのようにluaの中でリスニング事件を実現します

3181 ワード

1
--EventManager.lua     Assets/GameRes/Lua/
local EventManager = {}

local listenerTable = { }

--             
EventManager.AddListener = function(eventType, listener,target)
    --      v     (nil   false),      error;   ,       。
    --assert (v [, message])
    assert(eventType,'eventType is nil!')
    local t = listenerTable[eventType]
    if not t then
        t = {}
        listenerTable[eventType] = t
    end
    --                 
    t[#t + 1] = {listener = listener , target = target}   
end

--    
EventManager.TriggerListener = function(eventType,arg)
    --pcall         f。            ,      ,   ,     
    --       
    local ok,errors= pcall(function()
        
        assert(eventType,'eventType is nil!')
        local t = listenerTable[eventType]
        if t then
            for i = #t,1,-1 do  --          
                if t[i] then
                    if t[i].target == nil then
                        t[i].listener(arg)
                    else
                        t[i].listener(t[i].target,arg)  --          
                    end
                end
            end
        end
    
    end)

    if not ok then 
        local errorMessage = "error on troggerListener , type is "..eventType.."
"..errors CS.UnityEngine.Debug.LogError(errorMessage) end end EventManager.RemoveListener = function (eventType,listener,target) assert(eventType,"eventType is nil!") local t = listenerTable[eventType] if t then if target then for i = 1,#t do if t[i].target == target and t[i].listener == listener then table.remove(t,i) break end end return end for i = 1,#t do if t[i].listener == listener then table.remove(t,i) break end end end end return EventManager

 
 
2
--EventType.lua      Assets/GameRes/Lua/
local EventType = {}

EventType.Test = 1
EventType.CreateUI = 2

return EventType

 
 
3.どのようにmain.lua呼び出し
--main.lua
local EventManager = require "EventManager"
local EventType = require "EventType"

function Awake()
    print("Lua Awake")
    EventManager.AddListener(EventType.Test,function(arg) print("Test"..tostring(arg))  end)
end

function Start()
    print("Lua Start")
    EventManager.TriggerListener(EventType.Test,"6666")
end


--     
function Update()
    --print("Lua Update")
end

function OnDestroy()
    print("Lua OnDestory")
end

function SceneLoaded(name)
    print("Lua SceneLoaded "..name)
    
end

function SceneUnloaded(name)
    print("Lua SceneUnloaded  "..name)
end

function OnApplicationFocus(focus)
    print("Lua OnApplicationFocus "..tostring(focus))
end

function OnApplicationPause(pause)
    print("Lua OnApplicationPause "..tostring(pause))
end

function OnApplicationQuit()
    print("Lua OnApplicationQuit ")
end