Point & Click to Move in Unity

This tutorial will cover implement a point and click system to move the player around a room. If you don’t have one already create a Player script, attach it to your player, and open it. The first step is to create a Move function and call it in the Update function.

Next, you need to add the code to detect where the mouse is being clicked. To do this first you need to check that the left mouse button was clicked, use Input.GetMouseButtonDown(0) to check this. Inside the if statement get the ray of the mouse position based off of the camera. Create a RaycastHit variable, this will get the output of the Raycast check. In an if statement call Physics.Raycast passing it the ray and the hit with a distance of 100. This will do the raycast for you to see if it hits anything. You can log the hit point to check how it is working.

Next, you are going to need access to the Nav Mesh Agent, so create a variable and then assign it in the start Menu. Don’t forget to include “using UnityEngine.AI” at the top so NavMeshAgent is recognized.

Now change the Debug.Log in your Move function to a call to agent.SetDestination.

At this point if you player is clipping through your game objects you will need to make sure they are set to static and then rebake your navigation.

Now your player will move where you click!




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store