This implements the PlayerPreferences as an Options class that provides a get and set interface for each of the preferences.
print (Options.masterVolume);
Options.masterVolume = 0.3f;
print (Options.masterVolume);
print (Options.difficulty);
Options.difficulty = 2;
print (Options.difficulty);
The levelUnlocked is implemented as an indexer property allowing e.g.:
print (Options.levelUnlocked[2]);
Options.levelUnlocked[2] = true;
print (Options.levelUnlocked[2]);
Here’s Options.cs
using UnityEngine;
public static class Options
{
// PlayerPreference manager implemented as Static class
// using Properties with get and set and an indexer
// for the levelUnlocked property
public static LevelUnlocked LevelUnlocked = new LevelUnlocked();
public static float masterVolume
{
get
{
return PlayerPrefs.GetFloat(MASTER_VOLUME);
}
set
{
if (value >= 0f && value <= 1f)
{
PlayerPrefs.SetFloat(MASTER_VOLUME, value);
}
else
{
Debug.LogError("Master Volume out of range");
}
}
}
public static int difficulty
{
get
{
return PlayerPrefs.GetInt(DIFFICULTY);
}
set
{
if (value >= 1 && value <= 3)
{
PlayerPrefs.SetInt(DIFFICULTY, value);
}
else
{
Debug.LogError("Difficulty out of range");
}
}
}
// Private constants
private const string MASTER_VOLUME = "masterVolume";
private const string DIFFICULTY = "dfficulty";
}
And here’s LevelUnlocked.cs
using UnityEngine;
public class LevelUnlocked
{
/*
This class allows for storing a boolean unlocked condition
using int values in Unity's PlayerPrefs.
It provides an indexer user interface alllowing
get and set access with the level nr as index:.
Options.levelUnlocked[level] = true;
*/
private const int NR_OF_LEVELS = 3;
private const string LEVEL_UNLOCKED = "level_unlocked_";
// bool[] _unlocked = new bool[NR_OF_LEVELS];
public bool this[int level]
{
get
{
if (validLevelNr(level))
{
var key = LEVEL_UNLOCKED + level.ToString();
var val = PlayerPrefs.GetInt(key);
return val == 1;
}
return false;
}
set
{
if (validLevelNr(level))
{
var key = LEVEL_UNLOCKED + level.ToString();
var val = value ? 1 : 0;
PlayerPrefs.SetInt(key, val);
}
}
}
private bool validLevelNr(int level)
{
if (level < 1 || level > NR_OF_LEVELS)
{
Debug.LogError("Level < 1 || level > NR_OF_LEVELS : " + level);
return false;
}
else
{
return true;
}
}
}