How to save a Color with Player Prefs

How to save a Color with Player Prefs

Early this year, I shared a Color Picker implementation using the Unity Canvas.

I’ve recently updated the Demo project with the possibility to save / restore the selected Color between gameplay sessions using Unity Player Prefs.

It’s pretty simple.

When the Color value changes you need to convert it into a string using the method ColorUtility.ToHtmlStringRGBA and save it using the PlayerPrefs.

var color = Color.white;

PlayerPrefs.SetString("color", ColorUtility.ToHtmlStringRGBA(color));
PlayerPrefs.Save();

To restore the selected color value, you use the method ColorUtility.TryParseHtmlString to convert the saved string back into a Color object.

var savedColor = PlayerPrefs.GetString("color", "");
if(ColorUtility.TryParseHtmlString("#" + savedColor, Color color))
{
    // Use the saved Color
}

Please note that you need to add a “#” to the color value to create a valid hex code.