How to set interactable false when we click a button in unity

123 views Asked by At

I don't want players to be able to click a button twice, so I'm trying to set the 'interactable' property of buttons to false when a player clicks on them. I don't want to individually define button objects for all the buttons because I'll have a varying number of buttons in different scenes, which would be inefficient. How can I set the 'interactable' property to false when a player clicks it (without individually defining each button) ?

public string password = "1234" ;
public GameObject circle;
public int circleCounter;
public int correctCounter;

public void Update()
{
    circleSpawner();
}

public void circleSpawner()
{
    if (Input.GetMouseButtonDown(0) && circleCounter < password.Length) 
    {
        Vector3 mousePosition = Input.mousePosition;
        mousePosition.z = 10;
        GameObject newObject = Instantiate(circle, mousePosition, Quaternion.identity,transform);
        newObject.transform.SetSiblingIndex(0);
        circleCounter++;
    }
}

public void correctPasswordClick()
{
    correctCounter++;
    if (correctCounter == password.Length)
    {
        Debug.Log("correct password");
    } 
}
2

There are 2 answers

1
Amin On

I hope that I've understood your problem correctly; But in order to get every object of a certain type in Unity at the current scene, you may use FindObjectsOfType<T>() and then you can simply iterate over the returned objects using Linq or simple loops to manipulate them as you want.

if (Input.GetMouseButtonDown(0) && circleCounter < password.Length) 
{
    FindObjectsOfType<Button>().ToList().ForEach
        (button => button.interactable = false);
    // rest of your code
}
0
AudioBubble On

Assuming you have a class, that is attached to the same GameObject as the Button component, then you could grab your Button with:

var button = GetComponent<Button>();

in Start or Awake and store it, and then in the click method do:

button.isInteractable = false; 

Hope this helps.