简体   繁体   中英

Driving in Tree Unity 3D C#

Hi guys i'm trying to drive in the my GameObject (The Player) in my Project, I want a script to navigate to a var in a script that is on another GameObject. It's not easy because there is Parents and children... Here is my tree:

>PlayerEntity
    >Canvas
        Gun_Name_Text
        Gun_Ammo_Text
    >Player
        Sprite

I want a script attached to 'Gun_Name_Text' to fetch a var in a script attached to 'Player', so i didnt manage to do it with :

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

PS: I prefer not to use GameObject.Find() Thanks in advance

As I said in the comments, the easiest way to do this would to be to just assign the variable in the inspector. However if you can't do this then you could simply use:

OtherScript otherScript = null;

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

Note: This will set otherScript equal to the first instance of the OtherScript that it finds in the child objects though. You will have to use GetComponentsInChildren if you have more than one OtherScript object in the children.

For your specific example you could use:

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

If you are calling this often then it would be wise to cache a refrence to the weapon script though. You will also have to do this if you want to modify the Ammo1 variable that is a member of the weapon class as it is passed to the var ammo1 by value and not by reference.

There are cases where my game object does not know everything that interacts with it. An example would be a destructible object. If I wanted to know so what I'm hitting that was destructible I'd have all destructible objects inherit from a base type or interface and search on that type. Here is an example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM