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 class, override the method, set to the output, and return when you handle the selector, or return to let the next source try.
SourceTryEvaluateSelectorselectorInfo.ResulttruefalseWrite the source
Override the method and set the to the output. Return when you handle the selector, or otherwise to let the next source try.
TryEvaluateSelectorselectorInfo.ResulttruefalseUse to read the value in scope, and to read the selector being evaluated.
selectorInfo.CurrentValueselectorInfo.SelectorTextIf 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 and its . This method runs when the source is registered, and again after the settings asset deserializes.
IInitializerInitialize(SmartFormatter)The following source returns a random number when it sees the selector. Combine it with the Choose formatter to produce different responses.
randompublic 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 |
|---|---|
| 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 instance, which avoids changing global behavior:
SmartFormattervar 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 and give it a public parameterless constructor so it can be added and saved with the settings.
[Serializable]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.