Unity localization

Unfortunately Unity doesn’t support a native localization system. I tried using Resources (.resx) from Visual Studio in Unity, but it couldn’t be initialized:
MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure „Irrelevant.Assets.Test.resources“ was correctly embedded or linked into assembly „e46f0a679b15cf745b8e1be9f452390f“ at compile time, or that all the satellite assemblies required are loadable and fully signed.

Nevertheless I found a simple self made localization class on the Unity forum and made some small tweaks to the TextManager:

[singlepic id=“298″ w=“870″]

using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System;

/// 
/// TextManager V2
/// Inspired by http://forum.unity3d.com/threads/35617-TextManager-Localization-Script
/// 
/// Reads text files in the 'AssetsResources' directory into a dictionary. The text file 
/// consists of one line that has the key name, a space and the actual text to display.
/// 
/// Example:
/// 
/// Assume you have a text file called English.txt in AssetsResourcesLanguages
/// The file looks like this:
/// 
/// hello Hello and welcome!
/// goodbye Goodbye and thanks for playing!
/// 
/// In Unity code you have to set the Language property with the English.txt asset once:
/// TextManager.LoadResource = "LanguagesEnglish";
/// 
/// Then you can retrieve text by calling:
/// TextManager.GetText("hello");
/// This will return a string containing "Hello and welcome!"
/// 
public class TextManager : MonoBehaviour
{
    private static readonly IDictionary TextTable = new Dictionary();
    
    private static TextAsset _asset;
    public static TextAsset Language
    {
        set
        {
            _asset = value;

            if (_asset == null)
            {
                Debug.LogError(String.Format("No valid asset file."));
            }
            else
            {
                LoadLanguage(_asset);
            }
        }
    }

    /// 
    /// Load a asset by its AssetName.
    /// 
    /// 
    /// The text file must be located within 'Resources' subfolder in Unity ('AssetsResources' in Visual Studio).
    /// 
    public static String LoadResource
    {
        set
        {
            Language = (TextAsset)Resources.Load(value, typeof(TextAsset));
        }
    }

    private TextManager() { }

    private static void LoadLanguage(TextAsset asset)
    {
        TextTable.Clear();

        var lineNumber = 1;
        using (var reader = new StringReader(asset.text))
	    {
	        string line;
	        while ((line = reader.ReadLine()) != null)
	        {
                var lineElements = line.Trim().Split(' ');
	            if (lineElements.Length > 1)
                {
                    var key = lineElements[0];
                    var val = lineElements[1];

                    if (key != null && val != null)
                    {
                        var loweredKey = key.ToLower();
                        if (TextTable.ContainsKey(loweredKey))
                        {
                            Debug.LogWarning(String.Format(
                                     "Duplicate key '{1}' in language file '{0}' detected.", asset.text, key));
                        }
                        TextTable.Add(loweredKey, val);
                    }
                }
                else
                {
                    Debug.LogWarning(String.Format(
                         "Format error in language file '{0}' on line {1}. Each line must be of format: key value", 
                          asset.text, lineNumber));
                }

	            lineNumber++;
	        }
	    }
    }

    public static string Get(string key)
    {
        var loweredKey = key.ToLower();

        var result = String.Format("Couldn't find key '{0}' in dictionary.", key);

        if (TextTable.ContainsKey(loweredKey))
        {
            result = TextTable[loweredKey];
        }

        return result;
    }
}

And here is an example, how to use the TextManager within a Unity GUI:

using UnityEngine;

public class Gui : MonoBehaviour
{
    public TextAsset Language;

    int _toolbarInt = 0;

    void Start()
    {
        if (Language == null)
        {
            Debug.LogError("Language asset must be set!");
        }

        TextManager.Language = Language;
    }

    void OnGUI()
    {
        // Wrap everything in the designated GUI Area
        GUILayout.BeginArea(new Rect(0, Screen.height - 100, Screen.width, 100));

        _toolbarInt = GUI.Toolbar(new Rect(0, 0, Screen.width, 100), _toolbarInt, 
              new string[] { TextManager.Get("tree"), TextManager.Get("house"), TextManager.Get("car") });

        GUILayout.EndArea();
    }
}

The language asset file must be dragged&dropped to the Language property of the Gui script, the asset file may look like this (German.txt):

tree Baum
house Haus
car Auto

The language can easily be changed during simulation time by setting another language asset file to the Gui or the TextManager class.


Beitrag veröffentlicht

in

von

Schlagwörter: