- Home /
On Button Click Enable - Disable GameObject Through Inspector
Through inspector on button click, how to enable and disable gameobject?
I have done this to enable and disable gameobject on button click but it is not working.
This can only be able to enable the gameobject but it can't able to disable it. So how can I achieve this?
Code for CustomToggle script:
public class CustomToggle : MonoBehaviour
{
bool isOn;
//
[SerializeField] GameObject onStateObj;
[SerializeField] GameObject offStateObj;
private void OnEnable()
{
isOn = false;
onStateObj.SetActive(false);
offStateObj.SetActive(true);
}
public void OnToggleButtonClick()
{
if (isOn)
{
// make this off
isOn = false;
onStateObj.SetActive(false);
offStateObj.SetActive(true);
}
else
{
// make this on
isOn = true;
onStateObj.SetActive(true);
offStateObj.SetActive(false);
}
}
}
We might need to see your custom toggle script to debug your implementation. Thanks.
I have updated the question with the code...
It looks like it would work for me. One thing to note, I found that gameObject.SetActive(True) wouldnt work for me in some cases because it couldnt find the disabled gameObject in the scene. Try disabling/enabling the gameObject, or hiding its components to make it invisible. @siddharth3322
Your script looks fine to me. Is the problem that your OnState gameObject remains active after the second click?
yes, gameobject always remains active because in inspector I have marked it in enable state. I want to make it like toggle behavior through the inspector rather than code.
Answer by jimmiewalker653 · Nov 26, 2020 at 04:42 PM
bool isOn;
[SerializeField] GameObject onStateObj, offStateObj;
public void OnToggleButtonClick()
{
isOn = !isOn;
if (isOn)
{
onStateObj.SetActive(false);
offStateObj.SetActive(true);
}
else
{
onStateObj.SetActive(true);
offStateObj.SetActive(false);
}
}
Then remove your GameObject.SetActive on your button click and use only the OnToggleButtonClick and you should be good to go.
No, you are not getting the inspector image properly, the code enable and disable toggle images object. While in inspector, I want to enable and disable dialog object "SoundControllerDialog"
Oh... ok... in that case you want to use [HideInInspector] above what you are trying to hide. If I understand what you are needing correctly.
Again you not understand :)
I don't want to hide and show within the inspector, I want to enable and disable dialog object within the actual game, on button click event.