[英]Driving in Tree Unity 3D C#
嗨,大家好,我想在我的Project的GameObject(玩家)中開車,我想讓一個腳本導航到另一個GameObject上的腳本中的var。 這並不容易,因為這里有父母和孩子……這是我的樹:
>PlayerEntity
>Canvas
Gun_Name_Text
Gun_Ammo_Text
>Player
Sprite
我想要附加到“ Gun_Name_Text”的腳本來獲取附加到“ Player”的腳本中的變量,所以我沒有設法做到這一點:
var ammo1 = GetComponentInParent<GameObject> ().GetComponent<weapon> ().weaponOn.Ammo1;
PS:我不想使用GameObject.Find()預先感謝
正如我在評論中所說,最簡單的方法是在檢查器中分配變量。 但是,如果您不能執行此操作,則可以使用:
OtherScript otherScript = null;
void Start()
{
otherScript = transform.root.GetComponentInChildren<OtherScript>();
}
注意:這會將otherScript
設置otherScript
等於它在子對象中找到的OtherScript
的第一個實例。 如果GetComponentsInChildren
有多個OtherScript
對象,則必須使用GetComponentsInChildren
。
對於您的特定示例,您可以使用:
var ammo1 = transform.root.GetComponentInChildren<weapon>().Ammo1;
如果您經常調用它,那么明智的做法是將對weapon
腳本的引用緩存起來。 如果要修改屬於weapon
類成員的Ammo1
變量,因為它是通過值而不是通過引用傳遞給var ammo1
,則還必須這樣做。
在某些情況下,我的游戲對象並不知道與其交互的所有內容。 一個示例是可破壞的對象。 如果我想知道我要破壞的是什么,我會讓所有可破壞的對象都從基本類型或接口繼承並在該類型上進行搜索。 這是一個例子:
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.