C# script to make camera zoom in and out while player is using mouse wheel. It shoud work both in 2D and 3D mode.

 

Content not available.
Please allow cookies by clicking Accept on the banner

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
Tagged on:     

4 thoughts on “Unity C# Zoom In And Out Mouse Wheel Input

  • August 29, 2017 at 6:03 pm
    Permalink

    Thanks. Works Great 🙂

    Reply
    • August 30, 2017 at 9:42 am
      Permalink

      I’m glad to hear that 🙂

      Reply
  • January 26, 2020 at 4:50 pm
    Permalink

    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.

    Reply
    • January 26, 2020 at 4:56 pm
      Permalink

      Oh, I got it! Thank you for this code, it works fantastically!

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close