The question is answered, right answer was accepted
Can't reactivate object after I set it to inactivate
I want to make an object disappear and reappear with a press of a button. Here's my code: void Update () { if (Input.GetKeyDown ("k")) { if (bar.active == false) { bar.SetActive(true); } if (bar.active == true) { bar.SetActive(false); } } }
When I press "k" it makes the object disappear, but when I press "k" again, it doesn't reappear. All help appreciated!
Is bar
the gameobject your script is attached to? If so, when the gameobject is disabled, the script is also disabled and the Update does not run anymore..... so you have to attach this script to another gameObject
Answer by PersianKiller · Jun 08, 2018 at 04:58 AM
the problem is here
public class test : MonoBehaviour {
public GameObject bar;
void Update () {
if (Input.GetKeyDown ("k")) {
if (bar.active == false) {
bar.SetActive(true);
}
if (bar.active == true) {
bar.SetActive(false);
}
}
}
}
}
you used 2 ifs ,so for the first time you can deactive the bar,then if you press K again ,in this line
if (bar.active == false) {
bar.SetActive(true);
}
you active the bar but at the next line
if (bar.active == true) {
bar.SetActive(false);
}
you are deactiving the bar !!!!
so you should change it to this
public class test : MonoBehaviour {
public GameObject bar;
void Update () {
if (Input.GetKeyDown ("k")) {
if (bar.active == false) {
bar.SetActive(true);
}
else if (bar.active == true) {
bar.SetActive(false);
}
}
}
}
also as that dude said ,you should not attach this srcipt to the bar .because if you press k it will deactive the bar and you cannot use it again.