Using Preference - sinusinu/Flora GitHub Wiki

Preference can be used to store values that must be consistent between launch sessions(e.g. Game Settings or High Score Table).

It is stored as a JSON file, and load/save is handled by the class itself.

Let's take a look!

Begin with Simple Program:

MyCore.cs

using Flora;
using Flora.Gfx;
using Flora.Util;
using System;

namespace FloraTest {
    class MyCore : FloraCore {
        Preference pref;

        public override void Prepare() {
            pref = new Preference(PathUtils.Relative("prefs.json"));

            if (!pref.ContainsKey("magic_number")) {
                pref.SetValue("magic_number", 123);
                pref.Save();
            }

            int magicNumber = pref.GetValueInt("magic_number");
            Console.WriteLine("Today's magic number is {0}!", magicNumber);
        }

        public override void Pause() {

        }

        public override void Resume() {

        }

        public override void Resize(int width, int height) {

        }

        public override void Render(float delta) {
            Gfx.Begin();
            Gfx.End();
        }

        public override void Cleanup() {

        }
    }
}

You can see the brief basics of the Preference here.

Upon execution, the application will print Today's magic number is 123! to the console.

On the executable path, prefs.json file will be found with content of {"magic_number":"123"}.
Notice that the magic_number is stored as "123", not 123. Preference stores everything as string.

How to use Preference

Preference can be loaded using new Preference(path). path is where the values get stored, so it must be writable.
(If file does not exist, Preference will try to create the file.)

Preference is consisted of key-value pair, just like Dictionary.

  • Preference.Contains(key) can be used to check if given Preference have a key.

  • Preference.GetValue*(key, [fallback]) can be used to retrieve values saved in Preference.

    • * can be String, Int, Float, Bool.
    • fallback will be returned when the given key is not found. To check if the key exists, use Contains(key).
  • Preference.SetValue(key, value) puts the given key-value pair into the preference.

  • Preference.Save() saves current preferences to a file.

    • It is recommended to call Save() after setting preferences.
⚠️ **GitHub.com Fallback** ⚠️