Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Disable button after clicking it

Discussion in 'Scripting' started by CaringKarol, Oct 19, 2019.

  1. CaringKarol

    CaringKarol

    Joined:
    Jan 22, 2018
    Posts:
    28
    Hi,

    I'm trying to create a function that reads a value contained in a button. If the value matches a value in a list, the button is supposed to disappear. It runs whenever the button is clicked (in the OnClick() field in the inspector). Unfortunately, I can't figure out how to have the script reference the button and have it disable itself.

    This is my code:
    Code (CSharp):
    1. public void CheckIfARequiredItem()
    2.     {
    3.         string slotValue = gameObject.GetComponent<SlotValue>().value;
    4.  
    5.         //see if the slot value is a required button
    6.         for (int i = 0; i < requiredItems.Length; i++)
    7.         {
    8.             if (slotValue == requiredItems[i].ToString())
    9.             {
    10.                 //add the item to what has been collected
    11.                 //and disable the button
    12.                 itemsCollected.Add(requiredItems[i].ToString());
    13.                 gameObject.SetActive(false);
    14.             }
    15.         }
    16.     }
    Your help would be greatly appreciated!
     
  2. KnightsHouseGames

    KnightsHouseGames

    Joined:
    Jun 25, 2015
    Posts:
    850
    Do you have a reference to the button somewhere in code where you can access it? Like in some sort of UI manager type script that has all of your UI elements in it as variables?
     
  3. CaringKarol

    CaringKarol

    Joined:
    Jan 22, 2018
    Posts:
    28
    I don’t have a specific script that has all of my ui elements in a variable, but i do have that button and two others referenced in an array in the same script my function is located. I’m not sure how I can have the function know what button is being pressed though since it’s meant to be used when the button is clicked.
     
  4. KnightsHouseGames

    KnightsHouseGames

    Joined:
    Jun 25, 2015
    Posts:
    850
    It's not the most elegant thing in the world, but you could always add a second OnClick event on the button itself.

    You can pass a single parameter though the button, have the button pass which number it is in your array as it's argument to a method that disables the button based on that array.
     
  5. CaringKarol

    CaringKarol

    Joined:
    Jan 22, 2018
    Posts:
    28
    Okay, I will try that.

    Thank you for your help.