Created
September 18, 2018 20:29
-
-
Save FuzzySlipper/fd8aa0b35d173b5769efa560ff5dc4b0 to your computer and use it in GitHub Desktop.
Example usage of runtime CastleDB files
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
| using System; | |
| using UnityEngine; | |
| using System.Collections; | |
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Linq; | |
| namespace PixelComrades { | |
| public static partial class GameData { | |
| private static string[] _fileExtensions = new []{".cdb", ".json"}; | |
| private static string _mainJsonPath = Application.streamingAssetsPath + "/GameData"; | |
| private static Enums _enums = new Enums(); | |
| private static Dictionary<string, Dictionary<string, LoadedDataEntry>> _sheets = new Dictionary<string, Dictionary<string, LoadedDataEntry>>(); | |
| private static Dictionary<string, LoadedDataEntry> _entriesByFullID = new Dictionary<string, LoadedDataEntry>(); | |
| public static Enums Enums { get { return _enums; } } | |
| public static void Init() { | |
| _sheets.Clear(); | |
| _enums = new Enums(); | |
| var allowedExtensions = new HashSet<string>(_fileExtensions, StringComparer.OrdinalIgnoreCase); | |
| var files = new DirectoryInfo(_mainJsonPath).EnumerateFiles().Where(f => allowedExtensions.Contains(f.Extension)); | |
| foreach (var file in files) { | |
| var db = new JsonDB(File.ReadAllText(file.FullName)); | |
| foreach (var dbSheet in db.Sheets) { | |
| Dictionary<string, LoadedDataEntry> sheet; | |
| if (!_sheets.TryGetValue(dbSheet.Key, out sheet)) { | |
| sheet = new Dictionary<string, LoadedDataEntry>(); | |
| _sheets.Add(dbSheet.Key, sheet); | |
| } | |
| for (int i = 0; i < dbSheet.Value.Count; i++) { | |
| var entry = dbSheet.Value[i]; | |
| sheet.SafeAdd(entry.ID, entry); | |
| _entriesByFullID.SafeAdd(entry.FullID, entry); | |
| } | |
| } | |
| } | |
| } | |
| public static LoadedDataEntry Get(string sheetName, string entryID) { | |
| if (!_sheets.TryGetValue(sheetName, out var sheet)) { | |
| return null; | |
| } | |
| return sheet.TryGetValue(entryID, out var entry) ? entry : null; | |
| } | |
| public static LoadedDataEntry Get(string fullEntryID) { | |
| return _entriesByFullID.TryGetValue(fullEntryID, out var entry) ? entry : null; | |
| } | |
| public static T Get<T>(string sheetName, string entryID, string field) { | |
| var entry = Get(sheetName, entryID); | |
| if (entry == null) { | |
| return default(T); | |
| } | |
| var cell = entry.Get(field); | |
| if (cell == null) { | |
| return default(T); | |
| } | |
| if (cell is LoadedDataCell<T> typeCell) { | |
| return typeCell.Value; | |
| } | |
| return (T) cell.Get; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment