06 寻找最近敌人

在每个物体身上挂载DemoHP类,可以通过GameObject.FindObjectsOfType<DemoHP>();得到所有type类型为DemoHP的物体数组,通过Vector3.Distance(a,b)计算a和b的距离

public class findMinDistanceDemoHp : MonoBehaviour
{
    Transform myTransform;
    DemoHP[] allEnemy;
    private void Start()
    {
        myTransform = this.transform;
        allEnemy = GameObject.FindObjectsOfType<DemoHP>();
        DemoHP minEnemy = FindEnemyByMinDistance(allEnemy);
        minEnemy.GetComponent<MeshRenderer>().material.color = Color.red;
    }
    public DemoHP FindEnemyByMinDistance(DemoHP[] allEnemy)
    {
        DemoHP min = allEnemy[0];
        float minDistance = Vector3.Distance(myTransform.position, min.transform.position);
        for (int i = 1; i < allEnemy.Length; i++)
        {
            float newDis = Vector3.Distance(myTransform.position, allEnemy[i].transform.position);
            if (newDis < minDistance)
            {
                minDistance = newDis;
                min = allEnemy[i];
            }
        }
        return min;
    }
}