How to get Mouse position in Viewport space in Unity

Notes:

How to get Mouse position in Viewport space in Unity:
- In Unity we have various properties and methods, which help us to get mouse position in screen space, view port space, world space etc.

How to get Mouse Position in viewport space:
- view port space is the "rendering area" of a camera on the screen space
- is a normalized between 0 and 1

Note: each camera in the scene has its own view port space coordinate system
- Bottom Left corner of the view port space is considered as (0, 0, 0)
- Top Right corner of the view port space is considered as (1, 1, 0)

W.K.T. we can customize the rendering area of a camera on the screen space, i.e. where this camera must be displayed on the screen space using Viewport Rect property of the camera component.

Camera.ScreenToViewportPoint() method:
public Vector3 ScreenToViewportPoint(Vector3 point)
- Converts and returns a given screen space point to viewport space point

Example Code:

using UnityEngine;

public class CameraController : MonoBehaviour
{
Camera mainCamera;

void Start ()
{
mainCamera = this.GetComponent<Camera> ();
}

void Update ()
{
if (Input.GetMouseButtonUp (0))
{
Debug.Log(mainCamera.ScreenToViewportPoint(Input.mousePosition));
}
}
}