(Unity)追跡ターゲットを動的に再設定する。

  • 初期の追跡ターゲットが途中で破壊された場合、次のターゲットを再設定する。

(スクリプト)

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

public class ArmyGreen : MonoBehaviour
{
    private GameObject[] targetBox;
    private GameObject target;
    private NavMeshAgent agent;

    void Start()
    {
        // 初期の追跡ターゲット設定
        targetBox = GameObject.FindGameObjectsWithTag("Blues");
        target = targetBox[Random.Range(0, targetBox.Length)];

        agent = GetComponent<NavMeshAgent>();
    }

    void Update()
    {
        if(target)
        {
            agent.destination = target.transform.position;
        }

        // 初期のターゲットが破壊されたら、次の追跡ターゲットを再設定する。
        if(!target)
        {
            targetBox = GameObject.FindGameObjectsWithTag("Blues");

            // 対象グループが全滅したら終了
            if(targetBox.Length != 0)
            {
                target = targetBox[Random.Range(0, targetBox.Length)];
            }
        }
    }
}