【问题标题】:Getting child object of gameObject in unity统一获取gameObject的子对象
【发布时间】:2016-03-01 10:49:07
【问题描述】:

我有对象“单位”和子对象“怪物和健康”。 我也有带有球体对撞机的对象塔。 另外,我在 Tower Object 中有 OnTriggerEnter(Collider co) 函数来检测 Unit。

当它出现时,例如我可以通过访问它来打印名称“Unit” co.gameObject.name,甚至是 co.name,我猜是一样的。

但是,例如,我怎样才能获得 unit 的第一个子对象。我的意思是 Monster 对象,但不是名称,而是 Unit 对象的 FIRST SUB OBJECT ?

更新

使用此代码:

void OnTriggerEnter(Collider co)
{
    Debug.Log(co.gameObject.transform.GetChild(0));
}

导致异常:

UnityException: Transform child out of bounds
Tower.OnTriggerEnter (UnityEngine.Collider co) (at Assets/Scripts/Tower.cs:19)

更新 2 打印(co.transform.childCount);给出 2

这是正确的,因为我有

Unit
>

Monster

HealthBar

子对象

更新 3 塔代号。 使用 UnityEngine; 使用 System.Collections;

public class Tower : MonoBehaviour
{
    // The Bullet
    public GameObject Bullet;

    // Rotation Speed
    public float rotationSpeed = 35;

    void Update()
    {
        transform.Rotate(Vector3.up * Time.deltaTime * rotationSpeed, Space.World);
    }

    void OnTriggerEnter(Collider co)
    {

        print(co.transform.childCount);

        if (co.gameObject.name == "Unit(Clone)")
        { 

            GameObject g = (GameObject)Instantiate(Bullet, transform.position, Quaternion.identity);
            g.GetComponent<Bullet>().target = co.transform;
        }
    }
}

这段代码以某种方式打印了两次

2
UnityEngine.MonoBehaviour:print(Object)
Tower:OnTriggerEnter(Collider) (at Assets/Scripts/Tower.cs:20)
0
UnityEngine.MonoBehaviour:print(Object)
Tower:OnTriggerEnter(Collider) (at Assets/Scripts/Tower.cs:20)

【问题讨论】:

  • 越界意味着变换中没有子级。你必须先检查一下。见docs.unity3d.com/ScriptReference/Transform-childCount.html
  • 我已经检查并收到 2,这意味着我真的有 2 个子对象。我现在能做什么?
  • 您确定您使用的是正确的游戏对象吗? OnTriggerEnter(Collider co) 中的 co 是进入实体。向我们展示您的所有代码。
  • 实际上,当我再次运行模拟时,我在调试 2 消息中看到。先是2,然后同时是0。怎么会?

标签: unity3d gameobject subobject


【解决方案1】:

您必须对 GameObject 的 transform 进行操作。你可以使用Transform.GetChild(int index)函数。

您可能首先必须检查是否有任何孩子,因为如果您超出数组范围,GetChild 会引发异常。为此,您必须使用Transform.childCount。

更多信息可以在这里找到:

http://docs.unity3d.com/ScriptReference/Transform.GetChild.html http://docs.unity3d.com/ScriptReference/Transform-childCount.html

【讨论】:

  • 成功了。问题在于第二个称为打印的子弹对象。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
  • 2012-09-16
  • 1970-01-01
相关资源
最近更新 更多