Saving player stats for each level, static class or not ?

I’m creating a LevelStats class that I will use to save information about each level, for example, the best time, the number of chests collected, number of stars won etc…

But I am not sure what the best way to build it is, as a static class with static functions, or as a normal class which I create new instances of for each level? The way I am saving values is: ProfileName.LevelName.StatName

If static, then I could save any stat from anywhere with:

LevelStats.SaveLevelBestLap( Application.loadedLevelName, laptime );

if not static, then I would need to create an instance of it in any class that will need to save stats:

public LevelStats levelStats = new LevelStats( Application.loadedLevelName );

levelStats.SaveLevelBestLap( laptime );

I’m looking for a few tips from you guys with experience with this type of stuff. Is using a static class a better fit?

Thanks guys!

Stephane

I think you want to google “Singleton” and have a look at the PlayerPrefs class.

A singleton setup basically looks something like this:

public class SaveData : MonoBehaviour {
    // This is the singleton bit
    SaveData instance = null;
    public SaveData Instance {
        get {return instance;}
    }

    void Awake() {
        if(instance != null) Debug.LogWarning("There is more than one instance of SaveData in the scene!!");
        instance = this;
    }

    public void DoSomething() {}
}

Then call with: SaveData.Instance.DoSomething();

You could also add a static wrapper method to the class like:

public static void DoSomethingStaticVersion() { Instance.DoSomething(); } // Note the name can’t be the same

Or make a shortcut class and put all the statics in there

public static class SD {
    public static DoSomething() { SaveData.DoSomething(); } // Different class, so can share name
}