Aimdown Sights Toggle

Here my sights script,

var gun : Transform;
var nextPos = 0.0;
var nextField = 40.0;
var nextPos2 = -0.2;
var dampVelocity = 0.4;
var dampVelocity2 = 0.4;
var dampVelocity3 = 0.4;

function Update () {
   var newPos = Mathf.SmoothDamp(gun.transform.localPosition.x, nextPos, dampVelocity, .3);
   var newField = Mathf.SmoothDamp(Camera.main.fieldOfView, nextField, dampVelocity2, .3);
   var newPos2 = Mathf.SmoothDamp(gun.transform.localPosition.y, nextPos2, dampVelocity3, .3);
   
   gun.transform.localPosition.x = newPos;
   gun.transform.localPosition.y = newPos2;
   Camera.main.fieldOfView = newField;
   
   if (Input.GetButton("Fire2")) {
       //adjust viewpoint and gun position
       nextField = 40.0;
       nextPos = .05;
       nextPos2 = -0.15;
       
       //slow down turning and movement speed
       GetComponent("MouseLook").sensitivityX = 2;
       camera.main.GetComponent("MouseLook").sensitivityX = 2;
       camera.main.GetComponent("MouseLook").sensitivityY = 2;
   } else {
       //adjust viewpoint and gun position
       nextField = 60.0;
       nextPos = 0.45;
       nextPos2 = -0.4;
       
       //speed up turning and movement speed
       GetComponent("MouseLook").sensitivityX = 6;
       camera.main.GetComponent("MouseLook").sensitivityX = 6;
       camera.main.GetComponent("MouseLook").sensitivityY = 6;
   }
}

And can you tell me how to toggle this?

I’m not going to write the code for you but to write a simple toggle do the following:

  1. Create a boolean variable to store the on/off state
  2. Change your if-statement with Input.GetButton to instead call Input.GetButtonDown, which becomes true only once on the frame the button was pressed
  3. Flip the boolean variable from true/false inside the if block
  4. Depending on the state of that variable setup your parameters as before