在我们的 Unity 前端中,给 Button 添加监听事件的时候,有两种方法:
1、通过 Inspector 信息面板上的进行拖拽添加
2、通过 代码: Button.OnClick.AddListener()方法
在 Lua 中添加 监听的话就是通过:
LuaBehaviour 脚本进行,在InitPanel函数中添加查找按钮的代码:
MainPanel = {}
local this = MainPanel
local transform;
local gameObject;
local Btn_StartPlay
--启动事件--
function this.Awake(obj)
gameObject = obj
transform = obj.transform
--print(this.transform.name)
this.InitPanel()
end
--初始化面板--
function this.InitPanel()
this.Txt_Info = transform:Find("Txt_Info").gameObject
this.Btn_ShowInfo = transform:Find("Btn_ShowInfo").gameObject
this.Btn_HideInfo = transform:Find("Btn_HideInfo").gameObject
end
function this.Update()
end
--单击事件--
function this.OnDestroy()
logWarn("OnDestroy---->>>");
end
MainCtrl = {};
local this = MainCtrl;
local transform
local gameObject
-- 构建函数--
function this.New()
return this;
end
function this.Awake()
panelMgr:CreatePanel('Main', this.OnCreate);
end
-- 启动事件--
function this.OnCreate(obj)
print("Awake开始")
gameObject = obj
transform = obj.transform
behaviour = gameObject:GetComponent('LuaBehaviour')
behaviour:AddClick(MainPanel.Btn_ShowInfo,function()
print("显示")
MainPanel.Txt_Info.gameObject:SetActive(true)
end)
behaviour:AddClick(MainPanel.Btn_HideInfo,function()
print("隐藏")
MainPanel.Txt_Info.gameObject:SetActive(false)
end)
end
AddClick方法有两个参数,第一个是按钮本身(上一步才引用过的),第二个是点击后的回调函数。
AddClick的具体实现可以可以在LuaBehaviour.cs中找到。