How to get mouse position in Unity (Old and New Input System)

Unity Input system returns the mouse position with a single command. But the mouse position cannot be directly used in the game. Unity returns the mouse position in pixels; you need to convert it into world space coordinates to use it in your game. In this tutorial, we will see how to get mouse position in Unity using both the old Input system and the new Unity input System. And also, how to use it in different scenarios of your game.

Get mouse position in old Unity Input system

Step1: Get Mouse position

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        Vector3 mousePos = Input.mousePosition;            
    }
}
Mouse Position on screen

Mouse position will be returned to the X and Y axis based on the width and height of the screen.

Step2: Convert mouse position to world Position (both 2D and 3D)

Mouse position obtained in the previous has zero value for the Z axis. When converting mouse position from screen to world point this may cause the object to vanish from the camera view. To avoid this, we give the cameras clip plane distance as the Z value.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        Vector3 mousePos = Input.mousePosition;   
        mousePos.z=Camera.main.nearClipPlane;
        Vector3 Worldpos=Camera.main.ScreenToWorldPoint(mousePos);  
        Vector2 Worldpos2D=new Vector2(Worldpos.x,Worldpos.y)
        //Worldpos2D is required if you are making a 2D game 
       
    }
}
On screen and world position

Step3: Use the mouse position in your game

Let’s instantiate a prefab in Unity at the mouse position

using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    public GameObject Player;
    bool player_dead;
    void Update()
    {
        Vector3 mousePos = Input.mousePosition;   
        mousePos.z=Camera.main.nearClipPlane;
        Vector3 Worldpos=Camera.main.ScreenToWorldPoint(mousePos);  
        if(player_dead)
        {
             Instantiate(Player, Worldpos, Quaternion.identity);
        }
       
    }
}
Example of using mouse position

Using mouse position in a 2D game

We can use the X and Y coordinates of our 3D world position to get the mouse position in 2D.

using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    public GameObject Player2D;
    bool player_dead;
    void Update()
    {
        Vector3 mousePos = Input.mousePosition;   
        mousePos.z=Camera.main.nearClipPlane;
        Vector3 Worldpos=Camera.main.ScreenToWorldPoint(mousePos);  
        Vector2 Worldpos2D=new Vector2(Worldpos.x,Worldpos.y)
        if(player_dead)
        {
             Instantiate(Player2D, Worldpos2D, Quaternion.identity);
        }
       
    }
}

Get Mouse position when the mouse is clicked

In the above example, the code will return the mouse position in all frames. If that is not what you want you can put in a condition like mouse click to get the mouse position. The old input system uses “Input.GetMouseButtonDown(0)” to get the mouse click. You can replace 0 with 1 or 2 depending on which mouse button you want to detect.

Here is an example code

using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    public GameObject Player;
    bool player_dead;
    void Update()
    {
       if (Input.GetMouseButtonDown(0)) // returns true when the mouse left button is pressed
      {
            Vector3 mousePos = Input.mousePosition;   
            mousePos.z=Camera.main.nearClipPlane;
            Vector3 Worldpos=Camera.main.ScreenToWorldPoint(mousePos);  
            if(player_dead)
           {
                 Instantiate(Player, Worldpos, Quaternion.identity);
           }
       }
    }
}

Get mouse position in New Unity input system

Step1: Install the new Input system

  1. Go to Window>Package Manager.
  2. Search for Input System and click install.
  3. You will see a pop up to enable backends click YES.
  4. The editor will restart and the old input system will be disabled.
Unity Package manager window to install the new input system

Step2: Modify the above code to suit the new input system

  1. Add using UnityEngine.InputSystem.
  2. Change Input.mouseposition to  Mouse.current.position.ReadValue()
using UnityEngine;
using System.Collections;
using UnityEngine.InputSystem;

public class ExampleClass : MonoBehaviour
{
    public GameObject Player;
    bool player_dead;
    void Update()
    {
        Vector3 mousePos = Mouse.current.position.ReadValue();   
        mousePos.z=Camera.main.nearClipPlane;
        Vector3 Worldpos=Camera.main.ScreenToWorldPoint(mousePos);  
        if(player_dead)
        {
             Instantiate(Player, Worldpos, Quaternion.identity);
        }
       
    }
}

Get mouse button down Unity new input system

Similar to the example in the old input system if you want to get the mouse position only when the left button is pressed you have to replace “Input.GetMouseButtonDown(0)” with “Mouse.current.leftButton.wasPressedThisFrame”.

Here is the sample code for that

using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    public GameObject Player;
    bool player_dead;
    void Update()
    {
       if (Mouse.current.leftButton.wasPressedThisFrame) // returns true when the mouse left button is pressed
      {
            Vector3 mousePos = Mouse.current.position.ReadValue();   
            mousePos.z=Camera.main.nearClipPlane;
            Vector3 Worldpos=Camera.main.ScreenToWorldPoint(mousePos);  
            if(player_dead)
           {
                 Instantiate(Player, Worldpos, Quaternion.identity);
           }
       }
    }
}

Hope it was helpful. If you have any other questions on getting mouse position, please leave it in the comment box below.

3 thoughts on “How to get mouse position in Unity (Old and New Input System)”

  1. This is a good tutorial and it was very helpful. It was also frustrating though since the there are a few capitalisation problems in the code which will result in confusing errors which inexperienced coders, (like myself), may not no how to fix for several minutes.

    So for posterity:
    public GameObject is correct not gameObject
    if statements have no capital I

    So if you see this maybe you can go back and fix it and otherwise maybe users can have a look at this comment.
    I still think this is a helpful resource! Just needed a little bit of troubleshooting on my part. Thanks.

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Why Creativity is must for game developers How to become a Unity developer? How to Become a Game Developer? VR Game dev Companies: Top 10 Programming Languages used by Unity
%d bloggers like this: