Mouse Look Script for Unity

The script below enables mouse-driven rotation movement with options to control the X-axis, Y-axis, or both concurrently. Ideal for creating immersive character controls or dynamic camera perspectives in Unity projects. Customize sensitivity and rotation constraints to tailor the experience to your specific needs.

Steps

  • Create a new script, name it 'SC_MouseLook', then paste the code below inside it.

'SC_MouseLook.cs'

using UnityEngine;

public class SC_MouseLook : MonoBehaviour
{
    public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    public RotationAxes axes = RotationAxes.MouseXAndY;
    public float sensitivityX = 15F;
    public float sensitivityY = 15F;

    public float minimumX = -360F;
    public float maximumX = 360F;

    public float minimumY = -60F;
    public float maximumY = 60F;

    float rotationY = 0F;

    void Update()
    {
        if (axes == RotationAxes.MouseXAndY)
        {
            float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
        }
        else if (axes == RotationAxes.MouseX)
        {
            transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
        }
        else
        {
            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
        }
    }

    void Start()
    {
        // Make the rigid body not change rotation
        if (GetComponent<Rigidbody>())
            GetComponent<Rigidbody>().freezeRotation = true;
    }
}
  • Attach the 'SC_MouseLook' script to your GameObject or Camera in Unity.
  • Choose rotation axes ("MouseXAndY", "MouseX", or "MouseY") in the Inspector.
  • Fine-tune mouse sensitivity with "sensitivityX" and "sensitivityY" parameters.
  • Optionally, set rotation constraints using "minimumX", "maximumX", "minimumY", and "maximumY".
  • Customize other parameters based on your project requirements.
  • Enter Play mode to test and observe the mouse-driven camera movement.
  • Adjust sensitivity and rotation constraints for desired behavior.
  • Integrate the GameObject with 'SC_MouseLook' into your larger Unity project.
Links
Unity 6