- Home /
SetActive not working
if have a script that is supposed to opens (sets active) an image and sets a bool to true when I click I and does the opposite when I click it again but It doesn't work, it doesn't change the bool or set SetActive to true I don't know what's wrong with it.
heres my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Crafting : MonoBehaviour {
public bool isOpen;
public void Start(){
gameObject.SetActive (false);
isOpen = false;
}
void Update () {
if (Input.GetKeyDown (KeyCode.I) && !isOpen) {
gameObject.SetActive (true);
isOpen = true;
}
if (Input.GetKeyDown (KeyCode.I) && isOpen) {
gameObject.SetActive (false);
isOpen = false;
}
}
}
Answer by OperationDogBird · Jul 15, 2017 at 11:54 AM
Once your GameObject is inactive, it will no longer run scripts.
You will need a different gameobject's script to set the state of this gameobject.
Answer by tanoshimi · Jul 15, 2017 at 08:52 AM
That's because in every frame in which I is pressed down, you're activating the object (first block of code) and then immediately deactivating it again (second block of code). You only want to execute one or the other, so use else.
if (Input.GetKeyDown (KeyCode.I) && !isOpen) {
gameObject.SetActive (true);
isOpen = true;
}
else if (Input.GetKeyDown (KeyCode.I) && isOpen) {
gameObject.SetActive (false);
isOpen = false;
}
@tanoshimi I tried this but it still did not work, hers my script now
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Crafting : $$anonymous$$onoBehaviour {
public bool isOpen;
public void Start(){
gameObject.SetActive (false);
isOpen = false;
}
void Update () {
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.I) && !isOpen) {
gameObject.SetActive (true);
isOpen = true;
}
else if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.I) && isOpen) {
gameObject.SetActive (false);
isOpen = false;
}
}
}
Your answer
Follow this Question
Related Questions
Entering false statement even it is at true state. 1 Answer
Scavenger Hunt List Bools Question 1 Answer
I'm having trouble setting a bool. 2 Answers
c# Ignoring conditional statement? 1 Answer
Enemy ignoring script 1 Answer