Simple toggle not working
public GameObject canvasInstr;
private bool instr = false;
void Start () {
canvasInstr.SetActive(false);
}
void Update () {
if(Input.GetKeyDown(KeyCode.I) && !canvasInstr){
canvasInstr.SetActive(true);
instr = true;
}
else if(Input.GetKeyDown(KeyCode.I) && canvasInstr){
canvasInstr.SetActive(false);
instr = false;
}
}
I really don't know what I am doing wrong , however this toggle only switch itself off once and never goes back on. Please help (Maybe has to do with the fact that I have 2 canvas with diffeent names?) Many thanks in advance!
Where is attached this script? If you disable the object holding this script (or one of its parent), Update
won't run anymore.
The script is not attached to the object I am disabling...which in this case is a canvas for instructions (I have another canvas for other setting but is not attached either to this other object canvas)
How, I see, yu are not checking the value of the boolean instr
but if the canvasInstr
exists:
Try this :
void Update () {
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.I)){
instr = !instr ;
canvasInstr.SetActive(instr );
}
}
Cool!! Thanks it works fine! I would never have seen it by myself! By the way how do I vote on comments?
Answer by DreadKyller · Dec 19, 2017 at 12:09 AM
The code !canvasInstr
is the most likely problem. canvasInstr is an object, not a boolean, objects are often computed as true if not null and false if null, since the object is not null it will always equate to true and thus it will always run the else condition. I think you meant to use !instr
instead.
Thanks Dread, yes this is the problem I have comented already above, Hellium give me the clue, but thanks anyway
strange, when I wrote this answer, it showed "0 comments" now it shows 4 ;/
Your answer
Follow this Question
Related Questions
[Resolved] Image not changing on Toggle 1 Answer
Make a button toggle between highlight and default graphics onClick? 1 Answer
If Else problem 1 Answer
toggle button blinks 1 Answer