- Home /
SetActive(true) not working
I created a virtual button so I can control a cube to have it disappear and appear. In this case i can make the cube disappear but it will not appear again.
using UnityEngine; using System.Collections; using Vuforia;
public class AnotherVirtualButtonScript : MonoBehaviour, IVirtualButtonEventHandler {
// Use this for initialization
void Start()
{
GameObject virtualButtonObject = GameObject.Find("cubeButton");
virtualButtonObject.GetComponent<VirtualButtonBehaviour>().RegisterEventHandler(this);
VirtualButtonBehaviour[] vbs = GetComponentsInChildren<VirtualButtonBehaviour>();
for (int i = 0; i < vbs.Length; ++i)
{
vbs[i].RegisterEventHandler(this);
}
}
public void OnButtonPressed(VirtualButtonBehaviour vb)
{
GameObject.Find("Cube").SetActive(false);
}
public void OnButtonReleased(VirtualButtonBehaviour vb)
{
GameObject.Find("Cube").SetActive(true);
}
// Update is called once per frame
void Update()
{
}
}
I'm not sure if its my code but how can I get this to work?
Answer by Bunny83 · Aug 01, 2018 at 07:26 PM
Well, if you have an issue with a method you use, you should consult the documentation. Have a look at GameObject.Find
Finds a GameObject by name and returns it.
This function only returns active GameObjects.
So of course when you disable the gameobject you can't find it again. You shouldn't even use Find that often. Just use it once in Awake or Start and save the reference in a variable:
GameObject cube;
void Start()
{
cube = GameObject.Find("Cube");
}
public void OnButtonPressed(VirtualButtonBehaviour vb)
{
cube.SetActive(false);
}
public void OnButtonReleased(VirtualButtonBehaviour vb)
{
cube.SetActive(true);
}
thanks for the help, i found this setup to work and also used ui buttons to solve my problem.
Your answer
![](https://koobas.hobune.stream/wayback/20220612172011im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
What's wrong code if-else with tag script ? 0 Answers
SetActive and prefabs not working 1 Answer
SetActive - setactive(true) for one object, setactive(false) to the rest 1 Answer
Array SetActive C# Unity 1 Answer
SetActive(true); not working 4 Answers