Button OnClick Applied To Whole Canvas?

Hello,

I’ve recently started learning Unity and I’ve come into a bit of a problem that I can’t seem to fix.

I’m simply trying to create a UI Button that when clicked will re-focus the camera (Zooming in to a character head).

I’ve tired attaching the below script to both the button, and to a game object and then using the onClick event to launch it, but whenever I click anywhere in the screen, it zooms in, when I only want it to happen on my Button Click.

Code:

#pragma strict

var target : Camera;
var zoom : int = 20;
var normal : int = 60;
var smooth : float = 5;

private var isZoomed = false;


function Start () {

}

function Update () { 
	if (Input.GetMouseButtonDown(0)){ isZoomed = !isZoomed; }
	{
		{
		//target.main.transform.Translate(1,1,1);
		//target.fieldOfView = 20;

			if(isZoomed == true)
			{
			target.fieldOfView = Mathf.Lerp(target.fieldOfView,zoom,Time.deltaTime*smooth);
			}
			
			else
			{
			target.fieldOfView = Mathf.Lerp(target.fieldOfView,normal,Time.deltaTime*smooth);
			}
		
		}  
	}
}

Any advice would be really helpful.

Many thanks!

Your script is specifically checking for a mouse button press. So it doesn’t matter what object you attach it to, it’s going to execute the code inside of the if mouse is pressed. It’s running this code inside of Update so it’s going to run every frame.

Add a method to your script called something like Zoom, and just put your zoom code in it, which is everything after the if. In pseudocode it would look something like this.

function Zoom()
{
  zoomed = !zoomed
  if zoomed
    set the zoomed field of view
  else
    set the unzoomed field of view
}

Completely get rid of the Update code.

Once you have that function, that’s what you want to call in the button click event.