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 on screen

using UnityEngine;
using System.Collections;

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

Input.mousePosition is in pixel coordinated and will vary depending on the device screen. Next, we need to convert this screen position to world position.

Mouse Position on screen

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

Mouse position obtained in the previous step 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.

If you do not provide a Z value for the mouse position before converting it into world position, then you will get the same world position every time, irrespective of the mouse position.

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 
       
    }
}
Screen position converted to world position.

Using the mouse position in your game

Let’s instantiate a prefab in Unity at the mouse position. We will create a cube prefab and instantiate it when the space bar is pressed.

  • Add a cube game object to your scene.
  • Reset the transform component of the cube.
  • Drag and drop the cube from Hierarchy to the project window to create a prefab.
  • Now delete the cube from the scene.
  • Add an empty game object and add a script called “ExampleClass” to it.
  • Copy and paste the code below to your script.
using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    public GameObject prefab;
    // Start is called before the first frame update
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            Vector3 pos=Input.mousePosition;
            pos.z=Camera.main.nearClipPlane;
            Vector3 world_pos=Camera.main.ScreenToWorldPoint(pos);
            Instantiate(prefab,world_pos,Quaternion.identity);
        }
        
    }
}
  • Save the script and go back to Unity
  • Assign your prefab to the script.

Now play the game and press the space key. You prefab should spawn near your mouse position. Now let’s see how to do it in 2D.

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. Simply changing the Worldpos variable to Vector2 will do. Here is the code to spawn your prefab at the mouse position when the space bar is pressed.

using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    public GameObject prefab;
    // Start is called before the first frame update
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            Vector3 pos=Input.mousePosition;
            pos.z=Camera.main.nearClipPlane;
            Vector2 world_pos=Camera.main.ScreenToWorldPoint(pos);
            Instantiate(prefab,world_pos,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.

Let’s modify the above example to spawn the prefab on mouse click.

using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    public GameObject prefab;
    // Start is called before the first frame update
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Vector3 pos=Input.mousePosition;
            pos.z=Camera.main.nearClipPlane;
            Vector2 world_pos=Camera.main.ScreenToWorldPoint(pos);
            Instantiate(prefab,world_pos,Quaternion.identity);
        }
        
    }
}

Get mouse position in New Unity input system

If you are wanting to use the new input system, then you need to install it using the package manager.

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: Getting Mouse position in new input system

We can use the old input system code with some minor modifications as shown below.

  1. Add using UnityEngine.InputSystem.
  2. Change Input.mousePosition to  Mouse.current.position.ReadValue()

Here is the code to get mouse position in new input system

using UnityEngine;
using System.Collections;
using UnityEngine.InputSystem;

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

Get Mouse position on mouse click in new input system

Similar to the example in the old input system if you want to get the mouse position only when the left mouse 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.

%d bloggers like this: