我有對象「單位」的子對象「怪物和健康 我也有球對撞機的對象塔 另外我有塔對象中的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)
出界意味着有沒有孩子在變換。你必須首先檢查。見http://docs.unity3d.com/ScriptReference/Transform-childCount.html –
我已經檢查過,我收到2,這意味着我trully有2個子對象。我現在能做什麼 ? – David
你確定你正在使用正確的遊戲對象嗎? OnTriggerEnter(Collider co)中的co是輸入實體。向我們展示你的所有代碼。 –