1
\$\begingroup\$

I have the following example component:

public class DoStuff : MonoBehaviour
{

    public GameManager Data; // data to be shared among components and scenes, 

    public bool Predicate()
    {
        return Data.State == Idle;
    }

    public void Execute()
    {
        if (!Predicate()) return;
        //Do stuff
    }
}

It needs to access data that I have in a data class (not a component) called GameInfo, which the GameManager creates on start. What is the 'best practice' for accessing data like that in a unity component.

  1. Make GameInfo static (or Unity equivalent)
  2. Drag the GameManager GameObject from my Scene on this component from the Editor
  3. Use FindObjectOfType(typeof(GameManager)) to find the data on Awake/Start
  4. Turn GameInfo into a component and attach to empty GameObject in my scene, then follow #2.
  5. Some other method?

Thoughts:

  1. Having come from working on Internal tools and webservices, making things Static is rarely a good idea, but maybe for Game development making my global game state data static is the exact thing to do.

  2. I don't have any problems with this other than it just feels strange, but that's probably just due to being new to this mindset.

  3. I believe this uses reflection to search, which if only done once at start would be no big deal, but I feel this option is less nice than #2.

\$\endgroup\$
1
\$\begingroup\$

I would recommend 4, Attaching your Component to a GameObject, but I would give it a unique tag as well. This would allow you to easily retrieve it with GameObject.FindGameObjectsWithTag("UniqueTag").GetComponent<GameManager>(.

Also, be aware that static classes don't actually keep their data between level transitions (which I assume you want to).
To do this you'll have to call Object.DontDestroyOnLoad() on the GameInfo object. Full tutorial here.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.