Search Unity

Question Localization: How to set strings via scripting?

Discussion in 'Localization Tools' started by -chris, Oct 17, 2022.

  1. -chris

    -chris

    Joined:
    Mar 1, 2012
    Posts:
    99
    A lot of the Localization examples explain how to get strings, but I am trying to set strings via scripting.

    How do I modify a TableEntry to set a string for a locale?

    Code (CSharp):
    1. [SerializeField] StringTableCollection unityStringTableCollection;
    2.  
    3. ...
    4.  
    5. foreach (StringTable stringTable in unityStringTableCollection.StringTables) {
    6.     string entryKey = "foo";
    7.     TableEntry tableEntry = stringTable.GetEntry(entryKey);
    8.  
    9.     // How to set strings for each locale from here?
    10. }
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    The editor example here shows a typical usage
    https://docs.unity3d.com/Packages/com.unity.localization@1.4/manual/Scripting.html

    This class is the interface for most editor scripting.
    https://docs.unity3d.com/Packages/c....Localization.LocalizationEditorSettings.html

    Is your script above something that will be in the player? StringTableCollection is an editor only class. Take a look at the sample code we have in the quick start or the docs for some ideas.

    If this is player then you probably want a LocalizedStringTable instead.
     
  3. -chris

    -chris

    Joined:
    Mar 1, 2012
    Posts:
    99
    Hi @karl_jones , thanks, I'm just after manipulating strings in the Editor, not the Player.

    The examples seem to be about creating tables and creating entries – not modifying entries.

    Which methods or properties do I need to be using to set a string?

    I want to be able to do something like:
    1. Get TableEntry using a key (as above in my code thus far)
    2. Then call something like, TableEntry.SetString(locale, newString);

    What APIs do I need to use?

    Or is it easier to just remove the keys and add them again with new values?
     
  4. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    You can call GetEntry and then set it's Value property or If you just want to update the localized value then you can also call AddEntry which will update or add a new entry.
    You should set the sharedtable data and the table dirty to ensure the changes are saved.
     
    -chris likes this.