Unity fifteen UGUI click event

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.

Here Insert Picture Description
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");
  }
}

Here Insert Picture Description
Then click on the Canvas and drag event of the Button.
Here Insert Picture Description
Here Insert Picture Description

Then select the function to run when clicked
Here Insert Picture Description
Here Insert Picture Description

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()
    {  
        
    }

}

Here Insert Picture Description

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.
Here Insert Picture Description

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);
     
    }
}
Published 56 original articles · won praise 24 · views 30000 +

Guess you like

Origin blog.csdn.net/u014196765/article/details/94390864
Recommended