问题描述
限时送ChatGPT账号..前言/*我最近开始搞混统一:像大多数人一样制作了初学者的乒乓球游戏,现在我一直在尝试使用 3d 对象.我的想法是制作一个塔防游戏,所以我有一个塔和一个临时目标假人.塔有一个脚本,它应该允许它找到最近的带有敌人标签的物体并画一条线,但这里是问题:*/
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:*/
我的 GameObject.FindGameObjectsWithTag("Enemy") 函数返回一个空数组,尽管场景中有一个标记的启用对象.
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.
推荐答案
如果你还没有调试过这段代码,你可以检查一下 if (tmpd <= range && dist > tmpd)
正在通过.
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
}
}
如果前面的例子不起作用,你可以使用这个:
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
}
}
这篇关于FindGameObjectsWithTag 不返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论