Change view if key is pressed

I am trying to change Camera view if user presses down a key.

if (Input.GetKeyDown("z"))
{
  // Change Camera fov to 20.
}
else if (Input.GetKeyUp("z"))
{
  // Change Camera fov to 10.
}

The problem is that makes me hold down the z on the keyboard and once I let it go I have to go the “else if (Input.GetKeyUp(“z”))” takes effect.

What I want is for the user to press z and until he presses it again the Camera stays with fov to 20.

How would I do this, I tried get key and it didnt work; almost like both if and else executed at the same time due to how fast the update method is being called.

Hey,

Using `Input.GetKey()` should work.....

Try this script:

function Update(){
    if(Input.GetKey("z")){
        //Change camera fov to 20
    }
}

I hope I fully understood what you were trying to do, which was change the fov to something while the z key is held down, and then change it back/to something else, once the z key is released.....

Hope this helps you!!!!!!

Comment back if you need more help!!!!!!

-Grady

Hi Grady, thanks for your post.
Your code doesn’t work, because if GetKey is not “z” then the else will always execute.

I tried different variations of the else, such as

function Update()
{
   if(Input.GetKey("z"))
   {
    //Change camera fov to 20
    }
    else if (Input.GetKeyDown("z"))  
    {      
     //Change camera fov to 10
    }
}

That doesn’t work either. Any ideas?

Hi i know the C# script for this


using UnityEngine;
using System.Collections;

public class FieldOfViewChange : MonoBehaviour {

//set this to your defualt / standard fov
private float FieldOfView = 80;

// Update is called once per frame
void Update () {
	//when Z hey is pressed
	if (Input.GetKeyDown(KeyCode.Z))
	{
		//change the fov to 20
		gameObject.transform.camera.fieldOfView = 20;
	}
	//when Z key is released 
	if (Input.GetKeyUp(KeyCode.Z))
	{
		//change the fov to 80
		//(set the fov number here, to match the fov number in the private float)
		gameObject.transform.camera.fieldOfView = 80;
	}
}

}

if got it!!!

please contact me for the code! :slight_smile:

iuripujol@hotmail.com