Search Unity

Accessing two components in the same object

Discussion in 'Scripting' started by epochplus5, Oct 27, 2020.

  1. epochplus5

    epochplus5

    Joined:
    Apr 19, 2020
    Posts:
    677
    if i want a reference to an animator and a text component in the same object, what is the best way?

    just a public Animator and a public Text and drag them in?

    or would you make a GameObject theObject?

    the second way im not too familiar with. How do you access components from theObject?
    do you still need to use getComponent?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    There are multiple ways, they all work fine; which is the best depends on how these things are logically used. In this script, is it fundamentally important that these two components are on the same object? Or, do these components just happen to be on the same object right now - if you use the script again later, might they be on different objects and still make sense?

    If they could be different objects, then use 2 different public members and drag both in.

    If they must be the same object, I recommend only referencing one manually, and getting the other one from that. You can use GetComponent to get one from the other. So like:
    Code (csharp):
    1. public Animator myAnimator;
    2. private Text myText;
    3. void Awake() {
    4. myText = myAnimator.GetComponent<Text>();
    5. }
    I generally recommend against using a GameObject-type public member (except for prefab references) unless no specific components are required for the functionality of the thing. That will help prevent NullReferenceExceptions if you accidentally drag the wrong object into the slot, for example. (If you reference the component directly, Unity won't let you drag it in in the first place if the object doesn't have that component attached. It's pretty much always better to discover an error while you're putting the thing together rather than discovering it during runtime.)
     
    Deleted User likes this.
  3. epochplus5

    epochplus5

    Joined:
    Apr 19, 2020
    Posts:
    677
    Thanks for that StarManta