- Home /
How to know if button was previously pressed
Hi there, I have a set of buttons in my scene under the same parent GameObject. In the script attached to the parent Game Object I need to know which of the buttons has been pressed in order to run different functions.
Since the isPressed() method of Buttons is protected and not publicly accessible, how can I understand which button is pressed?
What I am looking for is a function of this type:
private Button findClickedButton()
{
var buttonList = GameObject.FindObjectsOfType<Button>();
foreach (var curButton in buttonList)
{
// if(curButton.isPressed())
// return curButton;
}
}
Thanks for any support!
Answer by ShadyProductions · May 11, 2020 at 12:25 PM
In the OnClick event you can select the function you want to run when a specific button is pressed. If you have a button controller script on the parent you can select this script in your buttons and select this function to be executed.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonController : MonoBehaviour
{
private Dictionary<int, Button> _clickedButtons = new Dictionary<int, Button>();
public void ClickFunction(GameObject gameObj)
{
var button = gameObj.GetComponent<Button>();
if (button != null)
{
int uniqueId = gameObj.GetInstanceID();
if (!_clickedButtons.ContainsKey(uniqueId))
{
_clickedButtons.Add(uniqueId, button);
}
}
}
}
_clickedButtons.Values will contain all your pressed buttons.