(Unity)画面上にいる敵を、一番近いものから順番に倒していく(一番近い敵の見つけ方)

(スクリプト)

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

public class MinMax3 : MonoBehaviour
{
    private GameObject[] targets;

    private List<float> disList = new List<float>();

    // 初期値の設定(ポイント)
    private float min = 100;

    // 一番近い敵の取得
    private GameObject nearestEnemy;

    private int count;
    public GameObject shellPrefab;
    public AudioClip sound;

    void Update()
    {
        count += 1;

        if(count % 60 == 0)
        {
            StartCoroutine(MinLockOn());
        }
    }

    private IEnumerator MinLockOn()
    {
        targets = GameObject.FindGameObjectsWithTag("Enemy");

        // 敵が全滅したら終了。
        if(targets.Length == 0)
        {
            yield break;
        }

        // 画面上で一番近い敵を探す仕組み
        foreach(GameObject t in targets)
        {
            float distance = Vector3.Distance(transform.position, t.transform.position);

            disList.Add(distance);

            foreach(float d in disList)
            {
                if(d < min)
                {
                    min = d;

                    nearestEnemy = t;
                }
            }
        }

        nearestEnemy.GetComponent<MeshRenderer>().material.color = Color.red;

        // 一番近い敵の方向に向く。
        transform.root.LookAt(nearestEnemy.transform);

        yield return new WaitForSeconds(0.5f);

        // 砲弾発射
        GameObject shell = Instantiate(shellPrefab, transform.position, Quaternion.identity);
        Rigidbody shellRb = shell.GetComponent<Rigidbody>();
        shellRb.AddForce(transform.forward * 1000);
        Destroy(shell, 2.0f);
        AudioSource.PlayClipAtPoint(sound, transform.position);

        // 初期値に戻す(重要ポイント)
        min = 100;

        // リストも初期化する(ポイント)
        disList = new List<float>();
    }
}

(実行結果)

  • その時点で一番近い敵の色が赤くなる。
  • その敵の方向に向いて砲弾を発射すれば成功です。