FindGameObjectsWithTag not returning objects

霸气de小男生 提交于 2021-01-29 03:24:06

问题


PREAMBLE /* I have recently started messing about with unity: made a beginner's pong game as most do and I've been trying to work with 3d objects now. My idea was to make a tower defense game, so I have a tower and a temporary target dummy. The tower has a script which should allow it to find the nearest object with the enemy tag and draw a line to it, but here is the issue:*/

My GameObject.FindGameObjectsWithTag("Enemy") function is returning an empty array, although there is a tagged, enabled object on the scene.

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;
        }
    }
}

I've looked though a thousand other threads and cannot find what my problem is. Any help would be greatly appreciated.


回答1:


In case you haven't debugged this code you can check if if (tmpd <= range && dist > tmpd) is passing through.

But let's assume that you've debugged the code and it acctualy haven't found any object then i would suggest you to use this:

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
    }
}

EDIT:

In case previous example would not work, you can use this:

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
    }
}


来源:https://stackoverflow.com/questions/41018270/findgameobjectswithtag-not-returning-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!