- Home /
Best way to store settings?
Hi,
I tried to make our game as data driven as possible and for some settings that are final now, I rather to store them out of source codes in text format that would act like DOS days ini files used to do, just store settings.
I think the new days approach is XML or something but since XML is not very intuitive to edit since it's DOM-based and you have to tag everything, I was wondering if there is a simple way that lets me store some integer and floats in a text file and the game would read them upon compilation.
Thanks.
Answer by whydoidoit · Feb 18, 2014 at 01:06 AM
Sure you could stick them in a .txt file and make it a TextAsset then use something like this to read them (not tested, scripted in the answer box):
using System.Linq;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Settings {
static Dictionary<string, string> properties;
static Settings() {
var contents = (Resources.Load("settings") as TextAsset).text;
properties = contents.Split(new [] {'\n', '\r'}).Where(s=>s.length>2).Select(s=>{
var parts = s.Split(new [] {':'});
return new { key: s[0].Trim(), value: s[1].Trim() };
}).ToDictionary(s=>s.key, s=>s.value);
}
static string Get(string name, string defaultValue = "") {
return properties.ContainsKey(name) ? properties[name] : defaultValue;
}
static float GetFloat(string name, float defaultValue = 0f) {
return properties.ContainsKey(name) ? System.Convert.ToSingle(properties[name]) : defaultValue;
}
static int GetInteger(string name, int defaultValue = 0) {
return properties.ContainsKey(name) ? System.Convert.ToInt32(properties[name]) : defaultValue;
}
}
This requires the settings to be in a "Resources" folder with the name "settings" - the file looks like:
someName: someValue
someOtherName: 123
You read them like this:
var myValue = Settings.Get("someName");
var myOtherValue = Settings.GetInteger("someOtherName");
Personally I think X$$anonymous$$L is a pretty good format as it's great at describing more complex things, arrays etc.