Search Unity

Feedback When to refrence GameObjects?

Discussion in 'Scripting' started by devonmuhammad968, May 15, 2021.

  1. devonmuhammad968

    devonmuhammad968

    Joined:
    Sep 30, 2018
    Posts:
    41
    Hello so i just learned the ability to refrence other gameObjects and so when is the best time to refrence a gameobject like can you give me a short example on when i can use it
     
  2. Rule of thumb when you're a beginner:

    - when you want to change one or more value on a component on another game object (
    othergameobject.transform.position = Vector3.zero;
    )
    - when you want to call a method on another component which is on another gameobject
    othergameobject.GetComponent<Player>.Hurt(hp: 5);


    What do you mean about "what is the best time"? If you mean like in the execution order, then the best time is in the editor (inspector) or in
    Awake
    method. Then when you gained the reference to the other component on the other game object, then you can call it any time you see fit.
     
    devonmuhammad968 likes this.
  3. devonmuhammad968

    devonmuhammad968

    Joined:
    Sep 30, 2018
    Posts:
    41
    thanks in one of my projects i referenced a game object in a script where if a enemy collided with the assigned game object for it to hurt that specific object but i wanted someone to explain it further on when it's really a good time to reference a game object in a script.
     
  4. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    This isn't a question that can be answered in any meaningful way.

    'A really good time' to reference a game object is the time at which your program requires said reference.
     
    Vryken and lordofduct like this.
  5. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,528
    This!

    ...

    I was coming in here to basically say the same thing by saying:

    When you need it.

    ...

    Since GameObjects are basically the containers upon which all components are added to a scene. References to them are abundant.
     
  6. devonmuhammad968

    devonmuhammad968

    Joined:
    Sep 30, 2018
    Posts:
    41
    yea thanks