FindGameObjectsWithTag不返回对象

时间:2016-12-07 13:04:06

标签: c# unity3d unity5

前言/ * 我最近开始搞乱团结:像大多数人一样做了一个初学者的乒乓球比赛,我现在一直试图用3D对象。我的想法是做一个塔防游戏,所以我有一个塔和一个临时目标假人。塔有一个脚本,应该允许它找到与敌人标签最近的对象,并绘制一条线,但这是问题:* /

我的GameObject.FindGameObjectsWithTag(" Enemy")函数返回一个空数组,尽管场景中有一个标记的启用对象。

public class Attack : MonoBehaviour
{

    GameObject[] enemies;
    float dist;
    GameObject target = null;
    bool targeted = false;
    float range = 1000;

    bool FindTarget()
    {
        bool found = false;
        enemies = GameObject.FindGameObjectsWithTag("Enemy");
        //print(GameObject.FindGameObjectsWithTag("Enemy"));
        foreach (GameObject enemy in enemies)
        {
            float tmpd = Vector3.Distance(enemy.transform.position, transform.position);
            if (tmpd <= range && dist > tmpd)
            {
                dist = tmpd;
                target = enemy;
                found = true;
            }
        }
        return found;
    }

    // Update is called once per frame
    void Update()
    {
        if (!targeted)
            targeted = FindTarget();
        else {
            Debug.DrawLine(target.transform.position, transform.position, Color.red);
            dist = Vector3.Distance(target.transform.position, transform.position);
            if (dist > range)
                targeted = false;
        }
    }
}

我看了一千个其他线程,但找不到我的问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果您尚未调试此代码,则可以检查if (tmpd <= range && dist > tmpd)是否正在通过。

但是我们假设你已经调试了代码并且它确实没有找到任何对象,那么我建议你使用它:

var allObjects = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[]; // this will grab all GameObjects from the current scene!
foreach(GameObejct obj in allObjects) {
    if(obj.Tag == "Enemy") {
        // do some magic here
    }
}

修改

如果上一个示例不起作用,您可以使用:

List<GameObject> allObjects = new List<GameObject>();
Scene activeScene = SceneManager.GetActiveScene();
activeScene.GetRootGameObjects( allObjects );
foreach(GameObject obj in allObjects) {
    if(obj.Tag == "Enemy") {
        // do some magic here
    }
}