Show Canvas when button is clicked, Unity 5.2.3
Hi guys, I wanted to ask you a question about how I can activate and deactivate a canvas component using a button. I have this code:
public GameObject[] optionPanels;
public void openPanel(GameObject selectPanel)
{
foreach(GameObject opPanel in optionPanels)
{
opPanel.SetActive(false);
}
selectPanel.SetActive(true);
}
But I do not know how to turn it off when I click on the button again, help!
Answer by Hellium · May 30, 2018 at 12:38 PM
public GameObject[] optionPanels;
private bool[] panelsState ;
private bool panelOpen ;
// Specify this function in the `OnClick` callback of your button
public void TogglePanel(GameObject selectPanel)
{
if( panelOpen )
ClosePanel();
else
OpenPanel( selectPanel );
}
public void OpenPanel(GameObject selectPanel)
{
if( panelsState == null )
panelsState = new bool[optionsPanels.Length];
for( int i = 0 ; i < optionsPanels.Length ; ++i )
{
// Save the current state of the panels
panelsState[i] = optionsPanels[i].activeSelf;
optionsPanels[i].SetActive(false);
}
selectPanel.SetActive(true);
panelOpen = true ;
}
public void ClosePanel()
{
if( panelsState != null )
{
for( int i = 0 ; i < optionsPanels.Length ; ++i )
{
optionsPanels[i].SetActive(panelsState[i]);
}
}
panelOpen = false ;
}
It does not work, it does not activate the canvas... idem to disable it
Oh wait, you made an error In the declaration of a variable.
...
public GameObject[] optionsPanel[]; //not optionPanel
...
sorry, my bad :P
Your answer
Follow this Question
Related Questions
How to open and close a "message box"? 0 Answers
How to activate and deactivate child of an instantiated parent object, 1 Answer
Best practices: hierarchy does not seem possible because redefined method need other private methods 0 Answers
How to prevent child GameObject from rotating when it's parent rotates? 1 Answer
Where are the Hierarchy icon settings? 0 Answers