Dictionary, JSON and Streaming Assets
版本检查: 5.5
-
难度: 新手
In this live training example we will look at a common need for many games: localizing text into other languages. We will create a LocalizationManager class that loads a file with localized text, and a component that can be attached to a text field in order to populate it with the localized text at runtime. We will also look at loading and parsing JSON files, dictionaries and some data driven best practices.


Dictionary, JSON and Streaming Assets
新手 Scripting
Download the assets for this training here
LocalizationData
Code snippet
[System.Serializable]
public class LocalizationData
{
public LocalizationItem[] items;
}
[System.Serializable]
public class LocalizationItem
{
public string key;
public string value;
}
LocalizationManager
Code snippet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class LocalizationManager : MonoBehaviour {
public static LocalizationManager instance;
private Dictionary<string, string> localizedText;
private bool isReady = false;
private string missingTextString = "Localized text not found";
// Use this for initialization
void Awake ()
{
if (instance == null) {
instance = this;
} else if (instance != this)
{
Destroy (gameObject);
}
DontDestroyOnLoad (gameObject);
}
public void LoadLocalizedText(string fileName)
{
localizedText = new Dictionary<string, string> ();
string filePath = Path.Combine (Application.streamingAssetsPath, fileName);
if (File.Exists (filePath)) {
string dataAsJson = File.ReadAllText (filePath);
LocalizationData loadedData = JsonUtility.FromJson<LocalizationData> (dataAsJson);
for (int i = 0; i < loadedData.items.Length; i++)
{
localizedText.Add (loadedData.items [i].key, loadedData.items [i].value);
}
Debug.Log ("Data loaded, dictionary contains: " + localizedText.Count + " entries");
} else
{
Debug.LogError ("Cannot find file!");
}
isReady = true;
}
public string GetLocalizedValue(string key)
{
string result = missingTextString;
if (localizedText.ContainsKey (key))
{
result = localizedText [key];
}
return result;
}
public bool GetIsReady()
{
return isReady;
}
}
StartupManager
Code snippet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class StartupManager : MonoBehaviour {
// Use this for initialization
private IEnumerator Start ()
{
while (!LocalizationManager.instance.GetIsReady ())
{
yield return null;
}
SceneManager.LoadScene ("MenuScreen");
}
}
LocalizedText
Code snippet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LocalizedText : MonoBehaviour {
public string key;
// Use this for initialization
void Start ()
{
Text text = GetComponent<Text> ();
text.text = LocalizationManager.instance.GetLocalizedValue (key);
}
}
LocalizedTextEditor
Code snippet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class LocalizedTextEditor : EditorWindow
{
public LocalizationData localizationData;
[MenuItem ("Window/Localized Text Editor")]
static void Init()
{
EditorWindow.GetWindow (typeof(LocalizedTextEditor)).Show ();
}
private void OnGUI()
{
if (localizationData != null)
{
SerializedObject serializedObject = new SerializedObject (this);
SerializedProperty serializedProperty = serializedObject.FindProperty ("localizationData");
EditorGUILayout.PropertyField (serializedProperty, true);
serializedObject.ApplyModifiedProperties ();
if (GUILayout.Button ("Save data"))
{
SaveGameData ();
}
}
if (GUILayout.Button ("Load data"))
{
LoadGameData ();
}
if (GUILayout.Button ("Create new data"))
{
CreateNewData ();
}
}
private void LoadGameData()
{
string filePath = EditorUtility.OpenFilePanel ("Select localization data file", Application.streamingAssetsPath, "json");
if (!string.IsNullOrEmpty (filePath))
{
string dataAsJson = File.ReadAllText (filePath);
localizationData = JsonUtility.FromJson<LocalizationData> (dataAsJson);
}
}
private void SaveGameData()
{
string filePath = EditorUtility.SaveFilePanel ("Save localization data file", Application.streamingAssetsPath, "", "json");
if (!string.IsNullOrEmpty(filePath))
{
string dataAsJson = JsonUtility.ToJson(localizationData);
File.WriteAllText (filePath, dataAsJson);
}
}
private void CreateNewData()
{
localizationData = new LocalizationData ();
}
}