- Home /
Script only works onetime
Hi,
I tried to create a script which toggles a GameObject (in this case an information text) on or off:
using UnityEngine;
using System.Collections;
public class toggleInformation : MonoBehaviour {
public GameObject ObjectToToggle;
public bool active;
void Start() {
active = true;
}
public void toggle() {
Debug.Log ("toggle");
if (active = true) {
ObjectToToggle.SetActive(false);
active = false;
} else if (active = false) {
ObjectToToggle.SetActive(true);
active = true;
} else {
Debug.Log ("Error: active neither true nor false");
}
}
}
Unfortunately it only works to toggle off the GameObject (default: it is turned on when starting the game). Console shows only one "toggle" even though I pressed the button several times (button executes the script).
Any ideas? :-/
Thank you!
Answer by error031 · May 31, 2015 at 12:41 PM
Is your script attached to ObjectToToggle? If it is, there is problem, because when ObjectToToggle is inactive, all scripts attached to it will be inactive too. My suggestion is to attach script to other gameObject.
Thanks for your answer. The script is attached to an empty GameObject "_$$anonymous$$anager".
This script looks correct, can you post code in wich you call this toggle function?
Here are two screenshots. I'm using a button to call the function. As I already mentioned, the script is attached to "_$$anonymous$$anager" (see 2nd screenshot). Note: I got the same problem with another script (changeColor: changes the color of some GameObjects).
Thank you for supporting me!
I am so blind, i didn't saw that you wrote if (active = true)
ins$$anonymous$$d if (active == true)
Thats the whole problem my friend xD
Sorry that took me so long to notice this xD
I just stumble across this and saw that you can reduce your code quite a lot:
public void toggle() {
Debug.Log ("toggle");
ObjectToToggle.SetActive(active = !active);
}
Your answer
Follow this Question
Related Questions
GameObject.setActive(bool) is not activating my gameObject 1 Answer
How many times awake function is called when toggle on/off gameObjects with the same C# script 1 Answer
Use a toggle button to change a GameObjects visibility 2 Answers
how to know if GameObject is active without getting warning? 2 Answers