Files

120 lines
2.8 KiB
GDScript

## PlayerPrefs.json example
"""
{
"i":{
"useMusic":1,
"hyperCam":0
},
"f":{
"camDist":3.422428
},
"s":{
"playerName":"MarsRacer"
}
}
"""
class_name PlayerPrefs;
extends Object;
const _prefs_path : String = "user://PlayerPrefs.json";
static var _prefs_loaded : bool = false;
static var _int_prefs : Dictionary = {};
static var _float_prefs : Dictionary = {};
static var _string_prefs : Dictionary = {};
static func _load_prefs():
_prefs_loaded = true;
var jsonfile : FileAccess = FileAccess.open(_prefs_path, FileAccess.READ);
if jsonfile == null: return;
var jsontxt : String = jsonfile.get_as_text(true);
var json : Variant = JSON.parse_string(jsontxt);
if json == null || \
typeof(json) != TYPE_DICTIONARY:
return;
var jdict : Dictionary = json;
if jdict.has("i") && typeof(jdict["i"]) == TYPE_DICTIONARY:
_int_prefs = jdict["i"];
if jdict.has("f") && typeof(jdict["f"]) == TYPE_DICTIONARY:
_float_prefs = jdict["f"];
if jdict.has("s") && typeof(jdict["s"]) == TYPE_DICTIONARY:
_string_prefs = jdict["s"];
static func _save_prefs():
var json : Dictionary = {};
json["i"] = _int_prefs;
json["f"] = _float_prefs;
json["s"] = _string_prefs;
var jsonfile = FileAccess.open(_prefs_path, FileAccess.WRITE);
if jsonfile == null:
push_error("Failed to open/create \"" + _prefs_path + "\" for writing!");
return;
if !jsonfile.store_string(JSON.stringify(json)):
push_error("Failed to write PlayerPrefs to \"" + _prefs_path + "\"!");
static func GetInt(key : String, default_value : int) -> int:
if !_prefs_loaded:
_load_prefs();
if _int_prefs.has(key) && (_int_prefs[key] as int) != null:
return _int_prefs[key];
else:
return default_value;
static func SetInt(key: String, value: int) -> void:
if !_prefs_loaded:
_load_prefs();
if _int_prefs.has(key) and (_int_prefs[key] as int) == value:
return
_int_prefs[key] = value;
_save_prefs();
static func GetFloat(key : String, default_value : float) -> float:
if !_prefs_loaded:
_load_prefs();
if _float_prefs.has(key) && (_float_prefs[key] as float) != null:
return _float_prefs[key];
else:
return default_value;
static func SetFloat(key: String, value: float) -> void:
if !_prefs_loaded:
_load_prefs();
if _float_prefs.has(key) and (_float_prefs[key] as float) == value:
return
_float_prefs[key] = value;
_save_prefs();
static func GetString(key : String, default_value : String) -> String:
if !_prefs_loaded:
_load_prefs();
if _string_prefs.has(key) && (_string_prefs[key] as String) != null:
return _string_prefs[key];
else:
return default_value;
static func SetString(key: String, value: String) -> void:
if !_prefs_loaded:
_load_prefs();
if _string_prefs.has(key) and (_string_prefs[key] as String) == value:
return
_string_prefs[key] = value;
_save_prefs();