Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


Create a custom source

Add your own source to resolve selectors that the built-in sources don't handle.
Read time 2 minutesLast updated 6 days ago

Add your own source to resolve selectors that the built-in sources don't handle.
To create your own custom source, inherit from the
Source
class, override the
TryEvaluateSelector
method, set
selectorInfo.Result
to the output, and return
true
when you handle the selector, or return
false
to let the next source try.

Write the source

Override the
TryEvaluateSelector
method and set the
selectorInfo.Result
to the output. Return
true
when you handle the selector, or
false
otherwise to let the next source try.
Use
selectorInfo.CurrentValue
to read the value in scope, and
selectorInfo.SelectorText
to read the selector being evaluated.
If your custom source needs to be set up before it can be used properly (for example, if it needs to read the case-sensitivity setting), you can implement
IInitializer
and its
Initialize(SmartFormatter)
. This method runs when the source is registered, and again after the settings asset deserializes.
The following source returns a random number when it sees the
random
selector. Combine it with the Choose formatter to produce different responses.
public class RandomValueSource : Source { public override bool TryEvaluateSelector(ISelectorInfo selectorInfo) { if (selectorInfo.SelectorText != "random") return false; selectorInfo.Result = UnityEngine.Random.Range(1, 4); return true; } }

Smart String

Result

{random:choose(1|2|3):Hello|Greetings|Welcome}!
Welcome!

Register the source

Add the source to the default formatter so it is available everywhere on the current thread:
Smart.Default.AddExtensions(new RandomValueSource()); // "Welcome!" Smart.Format("{random:choose(1|2|3):Hello|Greetings|Welcome}!");
Or register it on a specific
SmartFormatter
instance, which avoids changing global behavior:
var smart = Smart.CreateDefaultSmartFormat(); smart.AddExtensions(new RandomValueSource());
You can also add a custom source to the project's default formatter without code: in the Smart Strings settings, select Add (+) on the Sources list and choose your source from the menu, which lists every available source type by name. Mark the class
[Serializable]
and give it a public parameterless constructor so it can be added and saved with the settings.
Sources are tried in order, so place your custom source where it should take priority over the built-in sources. Refer to Smart Strings settings for information on how to configure the order in which sources are tried.

Additional resources