Search Unity

Accessing Variables - Clarification needed!

Discussion in 'Scripting' started by Deadlyapples, Mar 3, 2018.

  1. Deadlyapples

    Deadlyapples

    Joined:
    Dec 30, 2013
    Posts:
    54
    So I have read most of the posts on here and other forums about reading and accessing variables on other scripts but I need some clarification.

    If I use StatsManager StatsManager = GetComponent<StatsManager():

    Is this looking for a script called StatsManager on the current object that this current script is applied to or is it looking for it globally as an asset, or is it even looking for and using it even if it is not even in the scene?

    I am trying to create a stamina, mana and health system based on stats stored in the StatsManager script that uses the StatsManager of the current object. It looks at the current stamina levels and allows or denies actions based on its value.

    At the moment it all works as stated above but I have a feeling that it is accessing the StatsManager scrip regardless of it being in the scene or not and is unrelated to the game object.


    Any help would be appreciated!
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Calls to GetComponent check the GameObject the script is attached to and nothing more. If it's not found, it returns null and you get the dreaded NullReferenceException error if you try to access data from it.

    There are other calls, such as GetComponentInChildren or GetComponentInParent that will traverse the hierarchy looking for the script.

    No similar calls exist that check your asset folder.