Skip to content

Commit

Permalink
Add helper to load CSV as dictionary
Browse files Browse the repository at this point in the history
Allows CSV parser to be used for reading more generic CSV files, provided they follow the same key,value format.
Also add string split helper to TextManager for text arrays.
  • Loading branch information
Interkarma committed Oct 10, 2023
1 parent fa56017 commit 521dd1e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Assets/Scripts/Game/StringTableCSVParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,31 @@ public static List<KeyValuePair<string, string>> Load(string filename)
return rows;
}

/// <summary>
/// Loads CSV file into a generic dictionary.
/// CSV must have 2 rows only - first row is key, second row is value.
/// Seeks mods first then StreamingAssets/Text folder.
/// All entries must have a unique key or exception thrown.
/// If "key,value" is first row then first row will be ignored as a header.
/// </summary>
/// <param name="filename">Filename of StringTable CSV file.</param>
/// <returns>Dictionary<string,string> for each row if successful, otherwise null or empty.</returns>
public static Dictionary<string, string> LoadDictionary(string filename)
{
Dictionary<string, string> dict = new Dictionary<string, string>();

var rows = Load(filename);
if (rows == null || rows.Count == 0)
return dict;

foreach (var kvp in rows)
{
dict.Add(kvp.Key, kvp.Value);
}

return dict;
}

/// <summary>
/// Parse source CSV data into key/value pairs separated by comma character.
/// Source CSV file must have only two columns for Key and Value.
Expand Down
10 changes: 10 additions & 0 deletions Assets/Scripts/Game/TextManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,16 @@ public bool TryGetLocalizedText(TextCollections collection, string key, out stri
return TryGetLocalizedText(GetRuntimeCollectionName(collection), key, out localizedString);
}

/// <summary>
/// Splits input string into array of strings using newline or return as separator.
/// </summary>
/// <param name="textList">Input string where each item is separated by newline or return.</param>
/// <returns>String array.</returns>
public string[] SplitTextList(string textList)
{
return textList.TrimEnd(trimAtEnd).Split(newlineSequences, StringSplitOptions.None);
}

#endregion

#region Private Localized Text Methods
Expand Down

0 comments on commit 521dd1e

Please sign in to comment.