
ナビメッシュエージェントで敵を巡回させながら、基本的な設定を調整してみます。まずシーンにPlaneオブジェクトを置いて、インスペクタでNavigation Staticにチェックをいれます。
NavigationウィンドウのBakeタブでBakeをクリックしてナビメッシュを作ります。

シーンに適当に敵のオブジェクトを置いて、ナビメッシュエージェントコンポーネントとスクリプトを付けます。スクリプトには目的地をアタッチします。

目的地は、シリンダーオブジェクトを小さくしてコライダーを削除したもので、Planeの表面に適当にいくつか配置して、全ての空のゲームオブジェクトの子にしました。スクリプトにアタッチしたのはこのルートの空のゲームオブジェクトです。



スクリプトでは、目的地の親のオブジェクトからランダムに目的地を選びます。
using UnityEngine;
using UnityEngine.AI;
public class AgentScript2 : MonoBehaviour
{
[SerializeField] Transform points;
NavMeshAgent agent;
// Start is called before the first frame update
void Start()
{
agent = GetComponent();
SetDestinationRandomly();
}
// Update is called once per frame
void Update()
{
if (!agent.pathPending && agent.remainingDistance < 0.5f)
{
SetDestinationRandomly();
}
}
void SetDestinationRandomly()
{
agent.destination = points.GetChild(Random.Range(0, points.childCount)).position;
}
}
Transform.GetChild()の引数にインデックスを渡して特定の子オブジェクトを得られるので、そのインデックスを0以上でchildCountより小さい整数からランダムで選んでいます。
agent.destination = points.GetChild(Random.Range(0, points.childCount)).position;
Update()では、目的地の近くに来たときに次の目的地をランダムで選ぶようにします。
if (!agent.pathPending && agent.remainingDistance < 0.5f)
{
SetDestinationRandomly();
}
これで敵を巡回させられるようになりました。また、敵の動き方はナビメッシュエージェントコンポーネントで変えられます。
敵の足が地面から浮いていたり地面に埋まっているときは、Base Offsetで調節します。


Speedで歩く速さ、Angular Speedで回転する速さを変えられます。Angular Speedを小さくすると、敵が方向転換したときに目的地の方向へゆっくり向くようになって、大きくすると素早く回転します。


Accelerationは加速度です。小さくすると、スピードを落とした後の立ち上がりが重い感じになります。

目的地付近でスピードが落ちるのは、Auto Brakingにチェックが入っているからのようです。チェックを外すとそのまま同じスピードで歩き続けます。

Stopping Distanceを大きくすると、敵が目的地の直前で立ち止まります。

これで敵の進み方をコントロールできます。