This script lets you choose the destination point on the NavMesh by clicking the mouse on the object’s surface. The position of the click is determined by a raycast, rather like pointing a laser beam at the object to see where it hits (see the page Rays from the Camera for a full description of this technique). Since the GetComponent function is fairly slow to execute, the script stores its result in a variable during the Start function rather than call it repeatedly in Update.
// MoveToClickPoint.cs
using UnityEngine;
using UnityEngine.AI;
public class MoveToClickPoint : MonoBehaviour {
NavMeshAgent agent;
void Start() {
agent = GetComponent<NavMeshAgent>();
}
void Update() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100)) {
agent.destination = hit.point;
}
}
}
}
//MoveToClickPoint.js
var agent: NavMeshAgent;
function Start() {
agent = GetComponent.<NavMeshAgent>();
}
function Update() {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit, 100)) {
agent.destination = hit.point;
}
}
}
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information