在 Unity 中,我如何让某物查看具有特定标签的最近对象?

问题描述 投票:0回答:1

我是新人,不确定这是不是一个愚蠢的问题。

我想让一些东西看最近的带有特定标签的物体。

我试过这段代码:

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

public class TowerScript : MonoBehaviour
{
    public GameObject.Enemy

    // Update is called once per frame
    Void; Update
        transform.LookAt(GameObject.Enemy);
    }
}
c# unity3d
1个回答
0
投票

你可以用这个代码找到对象

GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Enemy");

你可以用这个方法找到最近的物体

Transform GetClosestEnemy(Transform[] enemies)
{
Transform tMin = null;
float minDist = Mathf.Infinity;
Vector3 currentPos = transform.position;
foreach (Transform t in enemies)
{
    float dist = Vector3.Distance(t.position, currentPos);
    if (dist < minDist)
    {
        tMin = t;
        minDist = dist;
    }
}
return tMin;
}
© www.soinside.com 2019 - 2024. All rights reserved.