toggle input key

Hi all,

I am trying to modify something I learned in a Unity tutorial. I want to use the space bar as a toggle key for the following script, in which I switch the target object for a light; (both of the following scripts are attached to the light):

var switchToTarget : Transform;

function Update ()  {
	if (Input.GetKeyDown("space"))
    GetComponent(Follow).target = switchToTarget;
} 

and the Follow script looks like this:

var target : Transform;

function Update () {
	transform.LookAt(target);
}

I know that I’m missing the boolean, so to test the boolean, I first tried it out in a simple script (below), and was then going to integrate it into the two scripts I’m really using (above):

var changeToggle : boolean;

function Update (){
    if (Input.GetKeyDown("space")){
            if(changeToggle)
                Debug.Log ("switched target");
            else
                Debug.Log ("!switched target");
            	changeToggle = !changeToggle;
    }
}

But I can’t get even the sample script to work for me; the message only changes once. I cannot press the space bar down repeatedly and have the message change each time. How do I do this?

Thanks in advance.

you cant not use {} if you have more than one line.

So your else statement needs to be

else
{
Dubug.Log.....
ChangeToggle....
}

istead of

else 
Debug.Log
Chagne Toggle

Thanks for going through my message. Even though the preview of the message showed the code to be formatted correctly, it doesn’t seem to have done so in the actual message.

Anyways, I tried adding the parentheses, but am still having the same problem. If I press the space bar once, it reads the other statement, but if I press the space bar again, it doesn’t go back to the original statement.

okay, so it was working the entire time (after I added the parentheses, Anxo, thanks). I just had the console collapsed, duh.

If you put parentheses around the Debug.Log and changeToggle lines (as in Anxo’s answer), you’ll see the behavior you report, where the message only shows the first time. This is because the value of changeToggle is only flipped when changeToggle is false. You need the changeToggle = !changeToggle line to be called in either case, so take those parentheses off. In fact, I like to toggle the value first, then go through the if-then.

if (Input.GetKeyUp(KeyCode.Space)) mouseFlightMode = !mouseFlightMode;

if (mouseFlightMode) {
	applyForces();
	applyTorques();
}

changeToggle = !changeToggle needs to be outside of the if statement because it needs to change every time you press the key

    if (Input.GetKeyDown("Space")){
          
       changeToggle = !changeToggle;
			
	   if (changeToggle == true) {

		   Debug.Log("Toggle");
				
	   }else {
				
		   Debug.Log("!Toggle");

	    }

    }