Unity实现自动寻路

要点:
1、调出导航窗口:
unity3d 顶部菜单 → 窗口(window) → AI → 导航(Navigation)。
会弹出导航窗口,一般在检查器(Inspector)窗口右侧。

3、实体对象添加自动寻路组件:
选择实体对象 → 检查器窗口(Inspector)→  添加自动寻路组件(Nav Mesh Agent)→ 添加控制脚本。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.AI;   //自动寻路 AI ,头文件

public class KillerCtrl : MonoBehaviour
 {
        NavMeshAgent agent;  //自动寻路AI代理
         GameObject obj;

 void Awake()
 {
         agent = GetComponent();   // 获取对象的 NavMeshAgent 组件
 }

 public void MoveTo(Vector3 position)
 {
         agent.SetDestination(position);  //设置目的地,AI自动往目的地寻路,自动避障
         //agent.Resume();
 }

 public void Stop()
 {
        // agent.Stop();
 }

 void Update()
 {
         obj = GameObject.Find("Cube");
         MoveTo(obj.transform.position);  //朝cube的位置寻路
 }

}

你可能感兴趣的:(Unity实现自动寻路)