【问题标题】:How to use FindGameObjectsWithTag with transform.position如何将 FindGameObjectsWithTag 与 transform.position 一起使用
【发布时间】:2018-09-26 16:20:52
【问题描述】:

大家好,谁能给我一个方法,我的敌人如何用标签(“人类”)追逐多个目标?看来

target = GameObject.FindGameObjectsWithTag("Human").GetComponent<Transform>();

Transform 不适用于此。

【问题讨论】:

  • FindGameObjectsWithTag 返回一个数组,因此您将拥有许多对象。如果您想追逐多个目标,则必须存储数组,循环遍历它并存储每个“人类”变换。
  • @jiveturkey,您应该考虑添加此评论作为答案。
  • 一个有效的状态机应该只有一个目标,并且能够根据特定条件改变它的目标。

标签: unity3d


【解决方案1】:

GameObject.FindGameObjectsWithTag 函数返回一个 GameObject 数组。你可以这样使用它:

GameObject[] target = GameObject.FindGameObjectsWithTag("Human");

如果您需要Transform 的数组,请使用GameObject.FindGameObjectsWithTag 返回的游戏对象的大小创建新数组,然后循环复制它。您不需要 GetComponent 函数。此处应使用transform 属性。

GameObject[] target = GameObject.FindGameObjectsWithTag("Human");
Transform[] targetTransform = new Transform[target.Length];
//Copy the GameObject transform to the new3 transform array
for (int i = 0; i < target.Length; i++)
{
    targetTransform[i] = target[i].transform;
}

【讨论】:

  • 我怎么能用它来追逐人类? transform.position = Vector2.MoveTowards(target.position, target.position, moveSpeed * Time.deltaTime);
【解决方案2】:

@Programmer 是一个不错的解决方案,但随着我对 ECS 和结构效率的了解更多,一个干净的解决方案可能如下。未来的适应性也会更强。

[System.Serializeable]
public struct Human {
    Transform transform;
}

GameObject[] targets = GameObject.FindGameObjectsWithTag("Human");
List<Human> humans = new List<Human>();
foreach (GameObject target in targets) {
    Human human = new Human();
    human.transform = target.transform;
    humans.add(human);
}

它看起来更慢,并且它的初始设置可能是,但在路上的访问不会。如果不需要,您不应该处理直接数组,现在您有一个可扩展的 Human 对象。

【讨论】:

  • You shouldn't deal with straight arrays 你能扩展一下吗?为什么要在使用数据之前将FindGameObjectsWithTag 作为数组返回的数据包装在结构中?使用这种方法还会丢失 GameObject 类的所有属性和方法(transform 属性除外)。
  • 这是真的。您可以将 GameObject 保存在 Human 结构中,然后以这种方式引用转换。这可能有点矫枉过正,但我​​用它来将音频之类的东西与一个人联系起来
  • 感谢您的回复,但我的主要问题是将数组转换为结构的原因。具体来说,您对You shouldn't deal with straight arrays 的陈述对我来说很有趣。为什么不处理数组?我不是想争论,只是想了解您建议的方法的原因。我很想学点新东西!
猜你喜欢
  • 1970-01-01
  • 2021-01-02
  • 1970-01-01
  • 2023-03-13
  • 2014-09-25
  • 2016-01-30
  • 2015-12-13
  • 2020-09-15
  • 2020-06-03
相关资源
最近更新 更多