Gun doesn't zoom out

Hi all,

I have a problem with my weapon’s zoom script.
I have been stuck on this for hours now. I have visited many sites in hope of solving my problem, but to no avail!

I don’t think the problem has anything to do with Unity, but with my script instead.
The code works perfectly fine when I zoom in (holding right click), but doesn’t zoom out when I release right click and the animation has finished playing. It stays zoomed in! Once the animation has ended and I release right click, the weapon stays zoomed in.

The zoomIn() function works fine, but the gun doesn’t zoom out during the zoomOut() function. I know the zoomOut() function works fine, because the camera’s FOV resets back to what it was(60), but the animation doesn’t rewind (maybe because it’s stopped?). I have tried changing the animation’s time, changing its speed and rewinding and many other things. If I am fully zoomed in and I zoom in again (I right click once the animation has finished playing), the gun jumps back to its original position and plays the zoom animation again.

The script makes perfect sense to me, so I don’t know what is going on or how to fix it!

Below is my code:

#pragma strict

var arms : GameObject;
var zoomed : boolean = false;

function Update () {
	if (Input.GetMouseButton(1) && zoomed == false) {
		zoomIn();
	}
	if (!Input.GetMouseButton(1)) {
		zoomOut();
	}
}

function zoomIn() {
	if (Input.GetMouseButton(1)) {
		animation.Play("zoom");
		camera.main.fieldOfView = 50;
		arms.active = false;
		yield WaitForSeconds(0.3);
		zoomed = true;
	}
}

function zoomOut() {
	zoomed = false;
	if (zoomed == false) {
		animation.Rewind("zoom");
		camera.main.fieldOfView = 60;
		arms.active = true;
	}
}

Please help


Thanks in advance

Your script has several problems - some serious, some less so:

a.) The following line says, “In every frame, if the right mouse button is not being pressed, zoom out”.

if (!Input.GetMouseButton(1)) {
   zoomOut();
}

I think what you meant to say is “In the frame in which the right mouse button is released, zoom out” (big difference!):

if (Input.GetMouseButtonUp(1)) {
   zoomOut();
}

b.) Your zoomIn function checks to see if the right button is being pressed. This is totally unnecessary, since the only way the function can be called is when the button is pressed - the test will always be true. Just get rid of the if here:

function zoomIn() {
  if (Input.GetMouseButton(1)) {

c.) You can’t just put random Yield statements in the middle of functions - they need to be placed in coroutines - I’m surprised this doesn’t generate a compiler error:

yield WaitForSeconds(0.3);

d.) Your zoomOut function also begins with a pointless test - how is this if test ever not going to be true? Get rid of it:

zoomed = false;
  if (zoomed == false) {