Unity 3D: Get the position of a mouse-click in a 3D world

When navigating the mouse over the screen you only change two coordinates. A mouse cursor lives in a 2D world. In this article I will explain how you can get the position of a mouse click in a 3D world.

First, lets create a new Unity project. Name it as you like. Once the project is created, add a plane. scale the plane up. Next, ad some cubes and spheres.

Your scene should look something like below (does not need to be exactly the same, just add the plane, some cubes and spheres).

Next, Create a new material. Make it red. Also, ad another small sphere to your scene, drag the material to it so that you have a red sphere. Reset the sphere’s position (all 0). Now drag the sphere from the hierarchy to your assets folder. This will create a prefab from the red sphere. Rename the prefab to “RedSphere”, and delete it from your scene. We will use this red sphere to indicate where the mouse click appeared.

We want the game window to show the same as the designer window. For that purpose, make sure the designer/scene window shows all cubes and spheres. Select the camera, go to the menu [Game Objects]>[Align with view] to align the camera.

Now we need to make a script. This script will handle the mouse click. The script has to be attached to a gameobject in order to be activated in the screen. We will attach it to the camera. Create a new script, call it “ClickLocation” and add it to the camera.

Open the script.

To determine the click position of the mouse we will use ray casting. We will send a ray from the position of the camera to the position of the mouse. At the place where the ray collides with any object, that is where the mouse click is positioned.

To make this more visual, we will instantiate the red sphere prefab at the position of the mouse click. For this we’ll need a reference to the prefab in the script.

At the top of the script, make a serializable field of the type GameObject, with the name “redSphere”:

Save the script and return to the editor. The new field should now appear in the inspector:

Now drag the RedSphere Prefab to the Red Sphere field, or click the little circle at the right of this field and select the RedSphere from the list:

Now go back to your script. We will put the logic in the update method. This is what we will do:

1. Check if the mousebutton is released (we want the position of the mouse cursor when you release the left button);
2. If so, create a ray from the camera to the mouse position;
3. Cast this ray ( “fire the laser”). If it hits something, return the position where this hit occurred;
4. Instantiate a red sphere at the hit position.

Use the following code to accomplish this:

Save your script and run the game. When you click and release your button, a red sphere will be placed in 3D space!