C# script to make camera zoom in and out while player is using mouse wheel. It shoud work both in 2D and 3D mode.
using System.Collections; using System.Collections.Generic; using UnityEngine; // ? 2017 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Zoom : MonoBehaviour { public float zoomSpeed; public float orthographicSizeMin; public float orthographicSizeMax; public float fovMin; public float fovMax; private Camera myCamera; // Use this for initialization void Start () { myCamera = GetComponent<Camera>(); } // Update is called once per frame void Update () { if (myCamera.orthographic) { if (Input.GetAxis("Mouse ScrollWheel") < 0) { myCamera.orthographicSize += zoomSpeed; } if (Input.GetAxis("Mouse ScrollWheel") > 0) { myCamera.orthographicSize -= zoomSpeed; } myCamera.orthographicSize = Mathf.Clamp(myCamera.orthographicSize, orthographicSizeMin, orthographicSizeMax); } else { if (Input.GetAxis("Mouse ScrollWheel") < 0) { myCamera.fieldOfView += zoomSpeed; } if (Input.GetAxis("Mouse ScrollWheel") > 0) { myCamera.fieldOfView -= zoomSpeed; } myCamera.fieldOfView = Mathf.Clamp(myCamera.fieldOfView, fovMin, fovMax); } } }
Unity C# Zoom In And Out Mouse Wheel Input
Thanks. Works Great 🙂
I’m glad to hear that 🙂
Hi! Can I ask where should I connect this component? I am pretty much new into Unity development. I tried to connect this component to a “Main Camera” but it seems it’s not working :’) Thank you.
Oh, I got it! Thank you for this code, it works fantastically!
Thanks!