menu_bookDocumentation
LocalData static class: Server-side data persistence
LocalData Static Class API Reference
LocalData provides server-side data persistence that survives server restarts. It's useful for storing configuration, ban lists, player data, and other server state.
Type Signature
CSHARP
public static class LocalData
{
public static void Set<T>(string key, T value);
public static T Get<T>(string key, T fallback = default);
public static bool Has(string key);
public static void Delete(string key);
}Methods
Set<T>(string key, T value)
Serializes value to JSON and writes it to {key}.json under FileSystem.Data. The directory hierarchy is created automatically.CSHARP
LocalData.Set("bans", banDictionary);
LocalData.Set("config", serverConfig);Get<T>(string key, T fallback = default)
Reads and deserializes the value stored at key. Returns fallback if the file doesn't exist or deserialization fails.CSHARP
var bans = LocalData.Get<Dictionary<long, BanEntry>>("bans", new()) ?? new();
var config = LocalData.Get<ServerConfig>("config", new ServerConfig());Has(string key)
Returns true if a value has been stored at key.CSHARP
if (LocalData.Has("bans"))
{
// Load bans
}Delete(string key)
Deletes the value stored at key. No-op if it doesn't exist.CSHARP
LocalData.Delete("bans");File Storage
- Data is stored as JSON files in the server's data directory
- File path format: {key}.json
- Directory hierarchy is created automatically via FileSystem.Data.CreateDirectory()
- Uses FileSystem.Data.WriteJson() and FileSystem.Data.ReadJson() for serialization
Error Handling
- Get() catches exceptions and returns the fallback value
- Failed reads are logged with [LocalData] prefix
- Invalid JSON or deserialization errors are handled gracefully
Example: BanSystem
CSHARP
public sealed class BanSystem : GameObjectSystem<BanSystem>
{
private Dictionary<long, BanEntry> _bans = new();
public BanSystem(Scene scene) : base(scene)
{
_bans = LocalData.Get<Dictionary<long, BanEntry>>("bans", new()) ?? new();
}
public void Ban(Connection connection, string reason)
{
_bans[connection.SteamId] = new BanEntry(connection.DisplayName, reason);
LocalData.Set("bans", _bans);
}
}Use Cases
- Ban lists and moderation data
- Server configuration and settings
- Player statistics and progress
- Custom game state persistence
- Plugin/addon configuration
Notes
- Server-side only - does not work on clients
- Data is stored in the server's data directory
- Complex types must be JSON-serializable
- Use records or classes with public properties for best results
- For GameObject persistence, consider SaveSystem instead
Was this helpful?