Search Unity

How to access function from a script which is NOT attached to a GameObject

Discussion in 'Scripting' started by swanne, Jun 16, 2019.

  1. swanne

    swanne

    Joined:
    Dec 17, 2015
    Posts:
    10
    Hi All,

    I have 2 Scenes.

    In scene 1 there is a GameObject which contains a 'ScoreManager' script to manage a leaderboard.

    In scene 2, I want to access the 'DownloadScores' function of the 'ScoreManager' script.

    The problem is that the GameObject which contains the 'ScoreManager' script does exist in Scene 2, causing a NullReference error.

    Using DontDestroyOnLoad is not an option as the ScoreManager script references UI elements that are not present in scene 2.

    I have read about static variables and functions but that causes other problems.

    Any guidance would be very much appreciated.
    Using DontDestroyOnLoad is not an option as t
     
  2. ClaudiaTheDev

    ClaudiaTheDev

    Joined:
    Jan 28, 2018
    Posts:
    331
    You could create a prefab ScoreManager and create an object in each scene.
     
    swanne likes this.
  3. lumoconnor

    lumoconnor

    Joined:
    Jan 17, 2016
    Posts:
    27
    Any chance you could split the ScoreManager into two separate classes? One that updates/references UI elements in Scene 1, and another that is set to DontDestroyOnLoad, that contains whatever functions need to be referenced by Scene 2?

    It depends on what the class does, and what functionality Scene 2 needs to access.
     
  4. swanne

    swanne

    Joined:
    Dec 17, 2015
    Posts:
    10
    Thank you @Gor-Sky and @lumoconnor for taking the time to offer your advice. I chose to implement the specific functions of the ScoreManager script in the GameManager script. Feels a little like duplication and I'm sure their's a much neater way of doing it, but this way works :)

    Thanks again
     
  5. EdGunther

    EdGunther

    Joined:
    Jun 25, 2018
    Posts:
    183
    maybe create a scriptable object to hold data
     
  6. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    Your ScoreManager shouldn't have to reference any UI elements. ScoreManager should not be driving UI, it manages your score, hence what the name of it is. KISS

    Rather instead let your UI elements reference the ScoreManager. It updates itself based on the ScoreManager.