Created
March 29, 2023 21:56
-
-
Save Monsoonexe/bce056037eb3887825d1809e6791d19e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Richard Osborn | |
// A very simple, serializable database for storing primitive values in a scriptable object. | |
using System; | |
using System.Collections.Generic; | |
using UnityEngine; | |
/// <summary> | |
/// A simple database object that stores key-value pairs of primitive types. | |
/// </summary> | |
public class SimpleDatabaseAsset : ApexScriptableObject | |
{ | |
[SerializeField] | |
private List<DatabaseEntry> entries; | |
public void SetInt(string key, int value) | |
{ | |
var entry = GetOrCreateEntry(key); | |
entry.IntValue = value; | |
} | |
public int GetInt(string key, int defaultValue = default) | |
{ | |
var entry = GetEntry(key); | |
return entry != null ? entry.IntValue : defaultValue; | |
} | |
public void SetFloat(string key, float value) | |
{ | |
var entry = GetOrCreateEntry(key); | |
entry.FloatValue = value; | |
} | |
public float GetFloat(string key, float defaultValue = default) | |
{ | |
var entry = GetEntry(key); | |
return entry != null ? entry.FloatValue : defaultValue; | |
} | |
public void SetBool(string key, bool value) | |
{ | |
var entry = GetOrCreateEntry(key); | |
entry.BoolValue = value; | |
} | |
public bool GetBool(string key, bool defaultValue = default) | |
{ | |
var entry = GetEntry(key); | |
return entry != null ? entry.BoolValue : defaultValue; | |
} | |
public void SetString(string key, string value) | |
{ | |
var entry = GetOrCreateEntry(key); | |
entry.StringValue = value; | |
} | |
public string GetString(string key, string defaultValue = default) | |
{ | |
var entry = GetEntry(key); | |
return entry != null ? entry.StringValue : defaultValue; | |
} | |
private DatabaseEntry GetOrCreateEntry(string key) | |
{ | |
var entry = entries.Find(e => e.Key == key); | |
if (entry == null) | |
{ | |
entry = new DatabaseEntry(key); | |
entries.Add(entry); | |
} | |
return entry; | |
} | |
private DatabaseEntry GetEntry(string key) | |
{ | |
return entries.Find(e => e.Key == key); | |
} | |
[Serializable] | |
private class DatabaseEntry | |
{ | |
public string Key; | |
public int IntValue; | |
public float FloatValue; | |
public bool BoolValue; | |
public string StringValue; | |
public DatabaseEntry(string key) | |
{ | |
Key = key; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment