How to Show and Hide UI panel interchangeably with button onclick in unity 2017.1.of 3
Hello guys, i got this code from an online tutorial i watched, it's about showing and hiding panel with a button clicked interchangeably, however, this doesn't seem to work rightly in unity 2017, Could anybody please suggest the right way to go about this, i'd be very grateful
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShowHide : MonoBehaviour
{
public GameObject panel;
int counter;
public void SwitchShowHide()
{
counter++;
if (counter % 2 == 1)
{
panel.gameObject.SetActive (false);
}
else
{
panel.gameObject.SetActive (true);
}
}
}
Are you sure you have specified the SwitchShowHide
function in the OnClick
event of your button (in the Inspector)?
Answer by UnityCoach · Sep 18, 2017 at 09:33 AM
This is a bit odd to use an integer to hold a true/false state.
I would rather to it this way :
public class ShowHide : MonoBehaviour
{
public GameObject panel;
bool state;
public void SwitchShowHide()
{
state = !state;
panel.gameObject.SetActive (state);
}
}
Actually, panel is already the gameObject, so it would be :
panel.SetActive (state);
I've tried this and many other but still doesn't work rightly, when i added a debug.log of the current (Boolean)state to know what's happening, it's as if both states of the (Boolean)state variable is called on every click i.e both true and false is called simultaneously onclick ins$$anonymous$$d of switching values for each click
Answer by MrCringeGaming · Sep 18, 2019 at 09:41 PM
I'm using this code, but im running into the issue where they overlap when you click both buttons. I am trying to stop that from happening...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CloseOpenUI : MonoBehaviour
{
public GameObject upgPanel;
public GameObject rbupgPanel;
/* In order for this to work it must be attached to your
* gamemanager object & attached to the onclick function
* on the buttons
*/
public void UpgOpenPanel()
{
if (upgPanel != null)
{
bool isActive = upgPanel.activeSelf;
upgPanel.SetActive(!isActive);
}
}
public void RbOpenPanel()
{
if (rbupgPanel != null)
{
bool isActive = rbupgPanel.activeSelf;
rbupgPanel.SetActive(!isActive);
}
}
}