大家好,我正试图在我的项目中驱动我的GameObject(玩家),我想要一个脚本导航到另一个GameObject上的脚本中的var。这并不容易,因为有父母和孩子。。。这是我的树:
>PlayerEntity
>Canvas
Gun_Name_Text
Gun_Ammo_Text
>Player
Sprite
我想要一个附加到"Gun_Name_Text"的脚本来获取附加到"Player"的脚本中的var,所以我没能使用
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
。
对于您的具体示例,您可以使用:
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);
}
}
}