toggling GUI script not working

i made a script to toggle part of my GUI on and off, but it doesnt seem to be working correctly
when i press the key it turns off, but when i press it again it will not turn on again
whats wrong with it?

(almost forgot to mention, the script for this is NOT set on something with that tag, so its gameobject is not getting turned off… also the “onoff” variable is working fine, it gets ticked and unticked)

#pragma strict
var onoff : boolean;


function Update()
{
if(Input.GetKeyDown("`"))
{
	if(onoff == true)
	{
    	for(var go : GameObject in GameObject.FindGameObjectsWithTag("guitextstats"))
    	{
    	go.active = false;
    	}
    	onoff = false;
    }
    
    else if(onoff == false)
    {
    	for(var stop : GameObject in GameObject.FindGameObjectsWithTag("guitextstats"))
    	{
    	stop.active = true;
    	}
    	onoff = true;
    
    }
}   
    
    
}

Are you sure you don’t want to try doing something like this?

#pragma strict

var onoff : boolean;

function Update()
{
	if(Input.GetKeyDown("`")) {
		//Toggle onoff between true/false
		onoff = !onoff;
	}
}

function OnGUI()
{
	if(onoff) {
		//if true
		GUI.Label(Rect(20, 20, 300, 20), "onoff is on.");
	} else {
		//if false
		GUI.Label(Rect(20, 20, 300, 20), "onoff is off.");
	}
}

still no answer btw…

The problem is as you have set all tagged objects to inactive, when you try to set them active again GameObject.FindGameObjectsWithTag("guitextstats") returns no objects, it will not return an error as it is still syntactically correct, but no objects will be in the list that it does the for loop on.

To fix, you have to save the list of objects by finding them at the start in the (Start method):

var onoff : boolean;
var guiTextObjects : GameObject[];

function Start(){
	guiTextObjects = GameObject.FindGameObjectsWithTag("guitextstats");
}

function Update(){
	if(Input.GetKeyDown("`")){
		if(onoff == true){
			for(var go : GameObject in guiTextObjects){
				go.active = false;
			}
			onoff = false;
		}else if(onoff == false){
			for(var stop : GameObject in guiTextObjects){
				stop.active = true;
			}
			onoff = true;
		}
	}   
}

This is untested but I’m pretty sure it should work.

Scribe