Button added to UGUI of current events summarizes the three methods.
1, click the plus sign to add events directly, this method is most commonly used.
This method can add a function with arguments, but at most a number of parameters, if there are two parameters, Unity not displayed.
First, write a script ButtonClickFIrst, then this script to mount on Canvas.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonClickFIrst : MonoBehaviour
{
public void a()
{
Debug.Log("ccccccc");
}
}
Then click on the Canvas and drag event of the Button.
Then select the function to run when clicked
2, add in the code, add an event by AddListener
Put this script onto the Button you can add an event,
of course, you can also add other events, by AddListener.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonClick : MonoBehaviour
{
// Start is called before the first frame update
void b()
{
Debug.Log("aaaaaaaaaaaa");
}
void addFun()
{
Button a = transform.GetComponent<Button>();
a.onClick.AddListener(b);
}
void Start()
{
addFun();
}
// Update is called once per frame
void Update()
{
}
}
3, the interface to add events
Inheritance interfaces IPointerClickHandler, add an event.
This interface is the click event of the interface, there are a lot of other events interface can be directly inherited. Directly in the back, you can add an interface.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonClick : MonoBehaviour,IPointerClickHandler
{
// Start is called before the first frame update
void b()
{
Debug.Log("aaaaaaaaaaaa");
}
void addFun()
{
Button a = transform.GetComponent<Button>();
a.onClick.AddListener(b);
}
void Start()
{
addFun();
}
// Update is called once per frame
void Update()
{
}
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("clickCount:::"+eventData.clickCount);
}
}