Version: 2019.4
Telling a NavMeshAgent to Move to a Destination
Making an Agent Patrol Between a Set of Points

Moving an Agent to a Position Clicked by the Mouse

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;
            }
        }
    }
Telling a NavMeshAgent to Move to a Destination
Making an Agent Patrol Between a Set of Points
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961