0
\$\begingroup\$

I am working on creating an object to maintain state of the game, player data, etc. It is static (singleton lifecyle) through the life of my game.

I started down the path of a static class, with a static instance, like this:

public class PlayerState
{
    private static PlayerState DATA_INSTANCE = new PlayerState();
    public static PlayerState Instance
    {
        get { return DATA_INSTANCE;  }
    }
}

Then I started looking around and I see implementations that derive from UnityEngine.MonoBehaviour and implement the instance handling differently, adding the script to a game object and using DontDestroyOnLoad() to ensure it stays in memory.

So I am wondering: what is the correct idiomatic pattern in unity for a singleton type?

Do I really need all of the unity functionality of a UnityEngine.MonoBehaviour derived type (eg: Update()) for my static type?

I admit I am uneasy about static classes, in general. In this case, I am equally uneasy adding another type that potentially gets in the frame cycle when its not needed (I mean that unity will call the methods like Update() for every cycle).

Thnx Matt

\$\endgroup\$
4

1 Answer 1

2
\$\begingroup\$

Not every class in a Unity project must necessarily inherit from MonoBehaviour. If there is no good reason to attach an instance of your class to a specific GameObject and you don't have a reason why you would need it to implement any Unity event, then there is no reason why you need to make it one.

In fact putting the whole game state into a static class (implementing the singleton pattern or not) is my favorite way to share data between scenes.

\$\endgroup\$
1
  • \$\begingroup\$ Note also that static classes can't inherit from any parent class. Attempting to do so will throw a Static class 'X' cannot derive from type 'Y'. Static classes must derive from object compiler error. \$\endgroup\$ May 3, 2019 at 1:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .