Search Unity

OnClick method how to make the button non-interactable via code?

Discussion in 'Scripting' started by ktyzk7, Oct 16, 2019.

  1. ktyzk7

    ktyzk7

    Joined:
    Sep 4, 2019
    Posts:
    17
    I have the script on GameManager which affects various similar buttons. I want the button to be interactable=false when the onclick event runs.

    I can't have another onclick event because it's gonna be an if statement. How can I do that?
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Don't know what this part means. Generally a single event can trigger a bunch of different things if you want.

    But ultimately, you're going to have some code that runs when the button is clicked, and that code needs to include a line that sets interactable to false for that button.
     
    Joe-Censored likes this.
  3. ktyzk7

    ktyzk7

    Joined:
    Sep 4, 2019
    Posts:
    17
    So I did it with
    Code (CSharp):
    1.     public Button[] WeaponButton;
    Code (CSharp):
    1.     public void isMoneyEnoughForWeapons()
    2.     {
    3.         for (int i = 0; i < weapons.Length; i++)
    4.         {
    5.             Weapon = weapons[i];
    6.             if (money < Weapon.weaponPrice)
    7.             {
    8.                 WeaponButton[i].interactable = false;
    9.             }
    10.             else if(ownedWeapon[i] == false)
    11.             {
    12.                 WeaponButton[i].interactable = true;
    13.  
    14.             }
    15.         }
    I just want to know if there is something simpler; cause this needs to be updated from inspector when I add another button.
     
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Any solution is going to involve somehow making a list of which button corresponds to which weapon, so that you can check the appropriate price.

    However, you might find it more convenient to create just a single button in your scene, and then have your script make copies of it for each weapon. You'd still need a list of weapons, but the buttons could be updated automatically. The downside is that anything unique about a particular button (like its graphic, label, or position) needs to somehow be controlled from code instead of being set manually.
     
  5. ktyzk7

    ktyzk7

    Joined:
    Sep 4, 2019
    Posts:
    17
    Alright let's see how I can do that. Thank you for the response.