2016-05-10 52 views
0

嗨,大家好我想在我的項目中我的GameObject(球員)駕駛,我想要一個腳本導航到另一個遊戲對象上的腳本var。這並不容易,因爲有家長和孩子......這是我的樹:駕駛在樹團結3D C#

>PlayerEntity 
    >Canvas 
     Gun_Name_Text 
     Gun_Ammo_Text 
    >Player 
     Sprite 

我想連接到「Gun_Name_Text」來獲取在連接到「球員」腳本中的VAR的腳本,所以我沒有管理

var ammo1 = GetComponentInParent<GameObject>().GetComponent<weapon>().weaponOn.Ammo1; 

PS:用做我不喜歡使用GameObject.Find() 在此先感謝

+2

你爲什麼不把它分配給檢查員? –

+0

aaaaaah聰明的一個;)沒有想過 – Ay0m3

+0

我回答你如何通過代碼做到這一點,如果你想。請記住,如果獲得對「武器」腳本的引用,然後使用該引用修改「Ammo1」值,會更好。 :) –

回答

1

正如我在評論中說,最簡單的方式做到這一點會是隻分配變量的檢查。但是,如果你不能做到這一點,那麼你可以簡單地使用:

OtherScript otherScript = null; 

void Start() 
{ 
    otherScript = transform.root.GetComponentInChildren<OtherScript>(); 
} 

注:這將設置otherScript等於找到的子對象雖然OtherScript的第一個實例。如果孩子中有多個OtherScript對象,則必須使用GetComponentsInChildren

針對您的特殊例如,你可以使用:

var ammo1 = transform.root.GetComponentInChildren<weapon>().Ammo1; 

如果你常常調用這個那麼這將是明智的,儘管緩存refrence到weapon腳本。如果您想要修改Ammo1變量,該變量是weapon類的成員,因爲它將按值傳遞給var ammo1,而不是通過引用傳遞給var ammo1

+0

非常感謝,我只想顯示它 – Ay0m3

+0

王牌,那麼所有的酷。如果這是答案,請記住並接受! –

+1

嗨@ Ay0m3你需要選擇一個答案,這是很重要的,因爲你是一個新用戶。否則你會得到主持,永遠無法在這裏輕鬆做任何事情 – Fattie

0

有情況下,我的遊戲對象不知道與其交互的一切。一個例子就是一個可破壞的對象。如果我想知道我擊中的那個是可破壞的,我會從基類型或接口繼承所有可破壞的對象並在該類型上進行搜索。這裏有一個例子:

private void CheckForDestructables(Collider2D c) 
{ 
    this.Print("CheckForDestructables Called"); 
    string attackName = GetCurrentAttackName(); 
    AttackParams currentAttack = GetCurrentAttack(attackName); 
    D.assert(currentAttack != null); 
    this.Print("CheckForDestructables Called"); 

    if (currentAttack.IsAttacking && c.gameObject.tag == "Destructable") 
    { 
    List<BaseDestructibleScript> s = c.GetComponents<BaseDestructibleScript>().ToList(); 

    D.assert(s.Any(), "Could Not find child of type BaseDestructibleScript"); 

    for (int i = 0; i < s.Count(); i++) 
    { 
     s[i].onCollision(Movement.gameObject); 
    } 
    } 
}