Creating a custom source
You can create custom sources using the ISource interface.
To use a custom Source, add it to the Sources list in the LocalizationSettings.
Random Value Source Example
The following example shows how to create a source that generates a random number. This could then be combined with a choose Formatter to produce different random responses.
using UnityEngine;
using UnityEngine.Localization.SmartFormat.Core.Extensions;
[System.Serializable]
public class RandomValueSource : ISource
{
public int min = 1;
public int max = 5;
public string selector = "random";
public bool TryEvaluateSelector(ISelectorInfo selectorInfo)
{
if (selectorInfo.SelectorText != selector)
return false;
selectorInfo.Result = Random.Range(min, max);
return true;
}
}
Example Smart String | Result |
---|---|
{random:choose(1|2|3}:Hello|Greetings|Welcome|Hi}! | Welcome! |
Literal Text Source Example
The following example shows how to create a source that will convert the source value into a string, this could then be further processed.
using System;
using UnityEngine.Localization.SmartFormat.Core.Extensions;
[Serializable]
public class LiteralTextSource : ISource
{
public bool TryEvaluateSelector(ISelectorInfo selectorInfo)
{
if (selectorInfo.SelectorText.Length < 3)
return false;
int len = selectorInfo.SelectorText.Length;
if (selectorInfo.SelectorText[0] == '\"' && selectorInfo.SelectorText[len - 1] == '\"')
{
selectorInfo.Result = selectorInfo.SelectorText.Substring(1, len - 2);
return true;
}
return false;
}
}
Note
To use "
in the selectors it will need to be added to the Allowed Selector Chars. (menu: Edit > Project Settings > Localization > String Database > Smart Format > Parser)
Example Smart String | Result |
---|---|
{"This example allows you to use spaces".ToUpper} | THIS EXAMPLE ALLOWS YOU TO USE SPACES |
Hello {"Karl:t(highlight)} | Hello <color=red>Karl</color> This is using a template in the form <color=red>{}</color> . |