然后在你的界面里面写入监听按钮的代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using
UnityEngine
;
using
System
.
Collections
;
using
UnityEngine
.
UI
;
using
UnityEngine
.
EventSystems
;
using
UnityEngine
.
Events
;
public
class
UIMain
:
MonoBehaviour
{
Button
button
;
Image
image
;
void
Start
(
)
{
button
=
transform
.
Find
(
"Button"
)
.
GetComponent
<
Button
>
(
)
;
image
=
transform
.
Find
(
"Image"
)
.
GetComponent
<
Image
>
(
)
;
EventTriggerListener
.
Get
(
button
.
gameObject
)
.
onClick
=
OnButtonClick
;
EventTriggerListener
.
Get
(
image
.
gameObject
)
.
onClick
=
OnButtonClick
;
}
private
void
OnButtonClick
(
GameObject
go
)
{
//在这里监听按钮的点击事件
if
(
go
==
button
.
gameObject
)
{
Debug
.
Log
(
"DoSomeThings"
)
;
}
}
}
适用于直接获取场景中已经创建好的ui_button
如果是预制体,通过Instantiate()创建的话,如下即可
GameObject gameObject = Instantiate (PrefabObejct, Vector3.zero, Quaternion.identity) as GameObject;
gameObject.AddComponent<Button> ().transition = Selectable.Transition.None;
gameObject.GetComponent<Button> ().onClick.AddListener (delegate {
print(gameObject.name); }); |