Skip to content

Commit

Permalink
more work on the settings system
Browse files Browse the repository at this point in the history
  • Loading branch information
dooly123 committed Feb 4, 2025
1 parent 5e30c60 commit 6dea59b
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 88 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
public abstract class BaseSetting<T> : BasisISettingHandler<T>
public abstract class BasisBaseSetting<T> : BasisISettingHandler<T>
{
public string Identifier { get; private set; }
protected T defaultValue;
protected T currentValue;

public BaseSetting(string identifier, T defaultValue)
public BasisBaseSetting(string identifier, T defaultValue)
{
Identifier = identifier;
this.defaultValue = defaultValue;
Expand Down
18 changes: 16 additions & 2 deletions Basis/Packages/com.basis.settings/Scripts/BasisSettings.asmdef
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
{
"name": "BasisSettings"
}
"name": "BasisSettings",
"rootNamespace": "",
"references": [
"GUID:45c7722710e2a37438daaacbf1cd4ad1",
"GUID:6055be8ebefd69e48b49212b09b47b2f"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
115 changes: 36 additions & 79 deletions Basis/Packages/com.basis.settings/Scripts/BasisSettingsSaver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,12 @@
using UnityEngine;
using UnityEngine.SceneManagement;

[Serializable]
public class DataItem
{
public string identifier; // Unique identifier for the data item
public string value; // Value stored as a string
}

[Serializable]
public class SettingsData
{
// Using Dictionary for O(1) fast lookups
public Dictionary<string, DataItem> itemsDictionary = new Dictionary<string, DataItem>();

// Find item by identifier with O(1) lookup time
public DataItem FindItemByIdentifier(string identifier)
{
itemsDictionary.TryGetValue(identifier, out var item);
return item;
}
}

public static class BasisSettingsSaver
{
private const string FileName = "BasisSettings.json";
private static readonly string FilePath = Path.Combine(Application.persistentDataPath, FileName);

public static SettingsData SettingsData = new SettingsData();
private static bool dataLoaded = false;

// Events
public static event Action OnDataSaved;
public static event Action OnDataLoaded;
Expand All @@ -43,49 +20,23 @@ public static class BasisSettingsSaver
public static async void Initialize()
{
SceneManager.sceneLoaded += OnSceneLoaded;
if (!dataLoaded)
{
await LoadDataAsync();
dataLoaded = true;
}
await LoadDataAsync();
ApplyChanges();
}

/// <summary>
/// when a scene is loaded we call this from the delegate
/// </summary>
/// <param name="arg0"></param>
/// <param name="arg1"></param>
private static void OnSceneLoaded(Scene arg0, LoadSceneMode arg1)
{
// You can handle scene-specific logic here if needed
//apply data
ApplyChanges();
}

// Add new method to load custom settings
public static async Task LoadCustomSettings(IEnumerable<DataItem> customItems)
{
bool isDataModified = false;

foreach (var item in customItems)
{
var existingItem = SettingsData.FindItemByIdentifier(item.identifier);
if (existingItem == null)
{
// Add the custom item if not already in the data
SettingsData.itemsDictionary.Add(item.identifier, item);
isDataModified = true;

OnOptionLoaded?.Invoke(item);
}
else
{
// Optionally update existing items with new values
existingItem.value = item.value;
OnOptionLoaded?.Invoke(existingItem);
}
}

if (isDataModified)
{
await SaveDataAsync(); // Save the custom items only if modified
Debug.Log("Custom data successfully added.");
}
}

/// <summary>
/// save to json on disc
/// </summary>
/// <returns></returns>
public static async Task SaveDataAsync()
{
try
Expand All @@ -99,47 +50,53 @@ public static async Task SaveDataAsync()
}

string json = JsonUtility.ToJson(SettingsData, true);
await Task.Run(() => File.WriteAllText(FilePath, json));
Debug.Log($"Data successfully saved to {FilePath}");
await File.WriteAllTextAsync(FilePath, json);
BasisDebug.Log($"Data successfully saved to {FilePath}");

OnDataSaved?.Invoke();
}
catch (Exception ex)
{
Debug.LogError($"Error saving data: {ex.Message}");
BasisDebug.LogError($"Error saving data: {ex.Message}");
}
}

/// <summary>
/// load json data on disc
/// </summary>
/// <returns></returns>
public static async Task LoadDataAsync()
{
try
{
if (File.Exists(FilePath))
{
string json = await Task.Run(() => File.ReadAllText(FilePath));
string json = await File.ReadAllTextAsync(FilePath);
SettingsData = JsonUtility.FromJson<SettingsData>(json);
Debug.Log($"Data successfully loaded from {FilePath}");
BasisDebug.Log($"Data successfully loaded from {FilePath}");

OnDataLoaded?.Invoke();

// Invoke loading events concurrently
await Task.Run(() =>
{
foreach (DataItem item in SettingsData.itemsDictionary.Values)
{
OnOptionLoaded?.Invoke(item);
}
});
}
else
{
Debug.LogWarning("No save file found. Generating default data.");
BasisDebug.Log("No save file found. Generating default data.");
await SaveDataAsync(); // Save the default data if file doesn't exist
}
}
catch (Exception ex)
{
Debug.LogError($"Error loading data: {ex.Message}");

BasisDebug.LogError($"Error loading data: {ex.Message}");
}
}
/// <summary>
/// at runtime setup all the options
/// </summary>
public static void ApplyChanges()
{
// Invoke loading events concurrently
foreach (DataItem item in SettingsData.itemsDictionary.Values)
{
OnOptionLoaded?.Invoke(item);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using UnityEngine;

public class StringSetting : BaseSetting<string>
public class BasisStringSetting : BasisBaseSetting<string>
{
public StringSetting(string identifier, string defaultValue) : base(identifier, defaultValue) { }
public BasisStringSetting(string identifier, string defaultValue) : base(identifier, defaultValue) { }

// Custom logic to apply the setting, such as saving to a file
public override async void ApplySetting()
Expand Down
8 changes: 8 additions & 0 deletions Basis/Packages/com.basis.settings/Scripts/DataItem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System;

[Serializable]
public class DataItem
{
public string identifier; // Unique identifier for the data item
public string value; // Value stored as a string
}
2 changes: 2 additions & 0 deletions Basis/Packages/com.basis.settings/Scripts/DataItem.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using System;
using UnityEngine.UI;
using UnityEngine;
using TMPro;

public class SettingUIHandler<T> : MonoBehaviour
{
public BasisISettingHandler<T> setting;
public InputField inputField;
public TMP_InputField inputField;
public Dropdown dropdown;

// For generic settings, this will update the value based on the input field or dropdown selection
Expand Down
16 changes: 16 additions & 0 deletions Basis/Packages/com.basis.settings/Scripts/SettingsData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;

[Serializable]
public class SettingsData
{
// Using Dictionary for O(1) fast lookups
public Dictionary<string, DataItem> itemsDictionary = new Dictionary<string, DataItem>();

// Find item by identifier with O(1) lookup time
public DataItem FindItemByIdentifier(string identifier)
{
itemsDictionary.TryGetValue(identifier, out var item);
return item;
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 6dea59b

Please sign in to comment.