Home > Back-end >  How to detect if button is clicked unity?
How to detect if button is clicked unity?

Time:09-21

I am not sure how to test if a button is clicked in unity 19.4. This is the code I tested does anyone know how to test things in the Update Method?

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

public class Controller : MonoBehaviour
{

[Header("Button Objects")]
    public Button buttonOne;

void Update()
    {
        if (buttonOne.clicked == true)
        {

            Debug.Log("It worked :D");

        }
    }
}

CodePudding user response:

I would create a Script with a Click funktion, add it to the button and then, look in the inspector of the button and add your function as a click event.

CodePudding user response:

Buttons work by adding listeners to the event of their onclick. These listeners can be persistent or runtime listeners. Persistent listeners are assigned in the editor and the runtime listeners are assigned in code at runtime. Here is how you would assign a new listener in code.

public class Controller : MonoBehaviour
{
    [SerializeField] private Button btn = null;

    private void Awake()
    {
        // adding a delegate with no parameters
        btn.onClick.AddListener(NoParamaterOnclick);
           
        // adding a delegate with parameters
        btn.onClick.AddListener(delegate{ParameterOnClick("Button was pressed!");});
    }
    
    private void NoParamaterOnclick()
    {
        Debug.Log("Button clicked with no parameters");
    }
    
    private void ParameterOnClick(string test)
    {
        Debug.Log(test);
    }
}

In the above example, I am adding two listeners. I am not sure if the function you want to call will have parameters or not, so make sure to only add a single callback unless you want multiple functions called when your button is clicked.

Update is a method that is called every frame. Only put logic in here that is continually checked or updated often. A button should only react once it is clicked, which is why it has the onclick. Unity is already internally checking if a button is clicked by using its EventSystem and a series of GraphicalRaycasts.

I had asked which version of Unity you are in as in newer versions there is a newer UI flow called UI Builder which has a completely different method of adding onclick events.

  • Related