using NEG.Utils.Achievments.AchievmentTypes; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; namespace NEG.Utils.Achievments { [CreateAssetMenu(menuName = "Achievments/Config/Backend/Local")] public class LocalBackendConfig : ScriptableObject, IAchievmentBackendConfig { [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)] private static void Init() { #if LOCAL_ACHIEVMENT_BACKEND Achievment.BackendLabel = "LocalAchievments"; #endif } [SerializeField] private string saveLocation; public IAchievmentBackend ConstructBackend() { return new LocalBackend(saveLocation); } } /// /// This backend is not optimised at all, do not use in public builds /// public class LocalBackend : IAchievmentBackend { private string saveLocation; public LocalBackend(string saveLocation) { this.saveLocation = saveLocation; } public void AchievmentCompleted(AchievmentData achievment) { string id = achievment.Achievment.Id; JObject jobj = LoadJson(); JToken token = jobj[id]; if (token is not JObject achievmentObj) { achievmentObj = new JObject(); } achievmentObj["completed"] = true; jobj[id] = achievmentObj; SaveJson(jobj); } public void AchievmentStateChanged(AchievmentData achievment) { string id = achievment.Achievment.Id; JObject jobj = LoadJson(); JToken token = jobj[id]; if (token is not JObject achievmentObj) { achievmentObj = new JObject(); } switch (achievment) { case IntAchievmentData intAchievment: achievmentObj["data"] = intAchievment.CurrentProgress; break; case FloatAchievmentData floatAchievment: achievmentObj["data"] = floatAchievment.CurrentProgress; break; case ToggleAchievmentData toggleAchievment: achievmentObj["data"] = toggleAchievment.IsCompleted; break; } jobj[id] = achievmentObj; SaveJson(jobj); } public AchievmentData GetStoredAchivment(AchievmentDefinition definition) { JObject jobj = LoadJson(); JToken token = jobj[definition.Id]; if (token is not JObject) { return null; } AchievmentData achievment = definition.Construct(); switch (achievment) { case IntAchievmentData intAchievment: intAchievment.CurrentProgress = (int)token["data"]; break; case FloatAchievmentData floatAchievment: floatAchievment.CurrentProgress = (float)token["data"]; break; case ToggleAchievmentData toggleAchievment: toggleAchievment.CompletionState = (bool)token["data"]; break; } return achievment; } public void Update() { //Nothing here } private JObject LoadJson() { if (Directory.Exists(Path.GetDirectoryName(saveLocation)) && File.Exists(saveLocation)) { return JObject.Parse(File.ReadAllText(saveLocation)); } return new JObject(); } private void SaveJson(JObject obj) { if (!Directory.Exists(Path.GetDirectoryName(saveLocation))) { Directory.CreateDirectory(Path.GetDirectoryName(saveLocation)); } File.WriteAllText(saveLocation, obj.ToString(Formatting.Indented)); } } }