2016-03-01 72 views
-1

我有对象“单位”的子对象“怪物和健康 我也有球对撞机的对象塔 另外我有塔对象中的OnTriggerEnter(Collider co)函数,检测单位。获取游戏对象的子对象统一

当它我可以例如通过访问 co.gameObject.name,甚至co.name,我的猜测是一样的打印名“单位”。

但我怎么能例如,获取单位的第一个子对象,我的意思是怪物对象,但不是名字,而是单位对象的第一个子对象?

UPDATE

使用此代码:

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) 

UPDATE 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) 
+0

出界意味着有没有孩子在变换。你必须首先检查。见http://docs.unity3d.com/ScriptReference/Transform-childCount.html –

+0

我已经检查过,我收到2,这意味着我trully有2个子对象。我现在能做什么 ? – David

+0

你确定你正在使用正确的游戏对象吗? OnTriggerEnter(Collider co)中的co是输入实体。向我们展示你的所有代码。 –

回答

1

你必须对游戏对象的transform操作。您可以使用Transform.GetChild(int index)函数。

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

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

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

+0

检查更新,请。 – David

+0

它工作。问题在于子弹对象,其次是打印。非常感谢帮助! – David