Search Unity

Enable/Disable UI panels with corresponding buttons

Discussion in 'Scripting' started by V-J, Oct 16, 2019.

  1. V-J

    V-J

    Joined:
    Apr 1, 2015
    Posts:
    73
    In my scene i have 8 UI buttons and 8 corresponding ui panels.
    When a button is pressed i want to disable the latest active panel (if there is one) and enable the corresponding panel. How can i achieve this?
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    I would have all the panels in an array and loop through them. Pass an int to a method which sets the panels active based on their index and the passed int values.
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    The way I've done this in apps is to just track which panel is open. When I open a panel, I just set a variable "openedPanel" for example to that object. Then when I go to open another panel, I can check if I have a dialog opened, and close it before opening the new one.

    This can also allow you to just target that variable when you close a panel as at that point, you just know when you hit a close button, you just need to close the active panel.

    In the button clicked method, you can just use the predefined SetActive call and target whatever gameobject you want to turn on as well.
     
  4. V-J

    V-J

    Joined:
    Apr 1, 2015
    Posts:
    73
    @WarmedxMints @Brathnann
    Thx for your answers, If i understand correctly i have to create some sort of Panel Manager to keep track of the current panel being show. Clicking on a button will pass in a new panel to the manager. Then the previous panel is disabled and the new panel is set as the current one and activated.

    Is it posible to show some code how it will look like? because I'm not a pro programmer yet.
     
    Last edited: Oct 17, 2019
  5. V-J

    V-J

    Joined:
    Apr 1, 2015
    Posts:
    73
    Solved!
     
  6. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    It's actually possible to do this entirely with standard Unity components and no custom code, if you want:
    • Instead of using regular Buttons, use Toggles (these default to looking like checkboxes, but you can restyle them however you want)
    • Put them all in a Toggle Group so that turning one on automatically turns the rest off
    • Set up each Toggle's OnValueChange with a dynamic bool call to SetActive on the corresponding panel that you want it to show
     
    V-J likes this.