Point & Click to Move in Unity

Christian Carter
2 min readOct 26, 2021

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.

void Update()
{
Move();
}
void Move()
{
}

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.

if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
Debug.Log("Hit: " + hitInfo.point);
}
}

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.

using UnityEngine.AI;public class Player : MonoBehaviour
{
private NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}

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

if (Physics.Raycast(ray, out hitInfo))
{
agent.SetDestination(hitInfo.point);
}

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!

-Chris

--

--