【问题标题】:Driving in Tree Unity 3D C#在 Tree Unity 3D C# 中驾驶
【发布时间】:2016-05-11 00:45:14
【问题描述】:

大家好,我正试图在我的项目中驱动我的游戏对象(玩家),我想要一个脚本导航到另一个游戏对象上的脚本中的变量。这并不容易,因为有父母和孩子......这是我的树:

>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() 提前致谢

【问题讨论】:

  • 为什么不直接在inspector中赋值呢?
  • aaaaaah 聪明的一个 ;) 没想到
  • 如果你愿意,我回答了你如何通过代码来做到这一点。请记住,最好获取对 weapon 脚本的引用,然后使用该引用修改 Ammo1 值。 :)

标签: c# unity3d


【解决方案1】:

正如我在 cmets 中所说,最简单的方法是在检查器中分配变量。但是,如果你不能这样做,那么你可以简单地使用:

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

【讨论】:

  • 非常感谢,我只是想展示一下
  • Ace,那就太酷了。如果这是答案,请记住并接受!
  • 嗨@Ay0m3,您需要勾选答案,这很重要,因为您是新用户。否则,您将受到审核,并且永远无法在这里轻松地做任何事情
【解决方案2】:

在某些情况下,我的游戏对象并不知道与之交互的所有内容。一个例子是一个可破坏的对象。如果我想知道我击中的是什么是可破坏的,我会让所有可破坏的对象都继承自基本类型或接口并在该类型上进行搜索。这是一个例子:

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);
    }
  }
}

【讨论】:

    猜你喜欢
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多