如何使用标签获取最近的GameObject的NAME(string)

时间:2019-09-07 18:44:54

标签: c# unity3d

我正在尝试使我的播放器以unity2D漂浮在地面(污垢)上。为此,我需要知道玩家和最尘土游戏对象之间的距离。我已经有东西了,但是我不能让它返回壁橱污垢游戏对象的字符串名称。

float distance = GameObject.Find("Player").transform.position.y - 
GameObject.Find(FindClosestDirt()).transform.position.y;

public GameObject FindClosestDirt()
{
    GameObject[] gos;
    gos = GameObject.FindGameObjectsWithTag("Dirt");
    GameObject closest = null;
    float distance = Mathf.Infinity;
    Vector3 position = transform.position;
    foreach (GameObject go in gos)
    {
        Vector3 diff = go.transform.position - position;
        float curDistance = diff.sqrMagnitude;
        if (curDistance < distance)
        {
            closest = go;
            distance = curDistance;
        }
    }
    string closeDirtName = closest.ToString();
    return closeDirtName;
}

Unity显示此错误: 错误CS1503:参数1:无法从'UnityEngine.GameObject'转换为'string'。 我显然返回了 closest.ToString()。 我忽略了什么吗?

1 个答案:

答案 0 :(得分:0)

您要返回的GameObject不是函数定义中的字符串。如果希望它返回字符串,则应为public string FindClosestDirt()

但是,您已经拥有游戏对象,只需从函数中返回该对象即可。这样就消除了额外的Find调用。

您还可以通过在Awake()函数中获取其结果并将其保存在变量中来删除GameObject.Find("Player")

private GameObject player;

public void Awake()
{
    player = GameObject.Find("player")
}

public void Update()
{
    float distance = player.transform.position.y - FindClosestDirt().transform.position.y;
    //...
}

public GameObject FindClosestDirt()
{
    GameObject[] gos;
    gos = GameObject.FindGameObjectsWithTag("Dirt");
    GameObject closest = null;
    float distance = Mathf.Infinity;
    Vector3 position = transform.position;
    foreach (GameObject go in gos)
    {
        Vector3 diff = go.transform.position - position;
        float curDistance = diff.sqrMagnitude;
        if (curDistance < distance)
        {
            closest = go;
            distance = curDistance;
        }
    }
    return closest;
}

另一个可能更快的选项是向下投射射线,并使用它命中的第一个污垢。