Documentation

Unity Engine

Download Unity

Unity Engine

UnityEngine.SmartStringsModule

The Smart Strings module provides string formatting with named placeholders, pluralization, and conditional text, based on SmartFormat.
Read time 7 minutesLast updated 3 hours ago

Definition

  • Type: Module

Remarks

Smart Strings build dynamic text from a single template that references values by name rather than by position. A template can pull values from objects or dictionaries, choose between phrasings, pluralize words, and format lists, which makes it well suited to localized text.
This module is enabled by default in all new projects. To enable it in an older project, do the following in the Unity Editor:
  1. Select Window > Package Management > Package Manager to open the Package Manager.
  2. Select the Built-in section.
  3. Select the Smart Strings module and click Enable.
Alternatively, you can add this line to the Packages/manifest.json file to enable the module:
"com.unity.modules.smartstrings": "1.0.0",

Classes

Class

Description

AdditionalFormatDataProvides additional information to the smart formatter for sources and formatters to use during formatting.
BoolVariableA IVariable that holds a single bool value.
ByteVariableA IVariable that holds a single byte value.
ChooseFormatterOutputs one of several literal options, selected according to the input value.
ConditionalFormatterFormats primitive types by matching them against condition patterns.
CustomPluralRuleProviderProvides custom plural rules to Smart.Format.
DefaultFormatterPerforms default formatting, using the same logic as
string.Format
.
DefaultSourceEvaluates an index-based Selector. Include this source, if an indexed source shall be used just the way string.Format does.
DictionarySourceEvaluates sources of types IDictionary, generic IDictionary_2 and dynamic ExpandoObject. Include this source, if any of these types shall be used.
DoubleVariableA IVariable that holds a single double value.
FloatVariableA IVariable that holds a single float value.
FormatRepresents a parsed format string. Contains a list of FormatItems, including LiteralTexts and Placeholders. Note: Format is IDisposable.
FormatDelegateWraps a delegate so that it can be used as a parameter to any string-formatting method (such as Format). For example:
FormatDetailsContains extra information about the item currently being formatted. These objects are not often used, so they are all wrapped up here.
FormatItemBase class that represents a substring of text from a parsed format string.
FormatterBaseBase class that implements common IFormatter functionality.
FormatterSettingsClass for SmartFormatter settings. Properties should be considered as 'init-only' like implemented in C# 9. Any changes after passing settings as argument to CTORs may not have effect.
FormattingErrorEventArgsSupplies information about formatting errors.
FormattingExceptionAn exception caused while attempting to output the format.
FormattingInfoThe class contains the fields and methods which are necessary for formatting.
IntVariableA IVariable that holds a single integer value.
IsMatchFormatterFormats values by matching them against a regular expression, and can output matching group values.
KeyValuePairSourceEvaluates a Selector with a KeyValuePair_2. The key must be
string
, the value must be an Object.
ListFormatterFormats each item individually when the source value is an array (or supports ICollection). Syntax: #1: "format|spacer" #2: "format|spacer|last spacer" #3: "format|spacer|last spacer|two spacer" The format will be used for each item in the collection, the spacer will be between all items, and the last spacer will replace the spacer for the last item only. Example: CustomFormat("{Dates:D|; |; and }", {#1/1/2000#, #12/31/2999#, #9/9/9999#}) = "January 1, 2000; December 31, 2999; and September 9, 9999" In this example, format = "D", spacer = "; ", and last spacer = "; and " Advanced: Composite Formatting is allowed in the format by using nested braces. If a nested item is detected, Composite formatting will be used. Example: CustomFormat("{Sizes:{Width}x{Height}|, }", {new Size(4,3), new Size(16,9)}) = "4x3, 16x9" In this example, format = "{Width}x{Height}". Notice the nested braces.
LiteralTextRepresents the literal text that is found in a parsed format string.
LongVariableA IVariable that holds a single long value.
NestedVariablesGroupProvides a reference to a VariablesGroupAsset.
NullFormatterFormats
null
values.
ObjectVariableA IVariable that can reference an Object instance.
ParserParses a format string.
ParserSettingsClass for Parser settings. Properties should be considered as 'init-only' like implemented in C# 9. Any changes after passing settings as argument to CTORs may not have effect.
ParsingErrorEventArgsSupplies information about parsing errors.
ParsingErrorsRepresents parsing errors in a format string. This exception only gets thrown when Parser.ErrorAction is set to ThrowError.
PersistentVariablesSourceProvides global or local values that do not need to be passed in as arguments when formatting a string. The smart string should take the format {groupName.variableName}. e.g {global.player-score}. Note: The group name and variable names must not contain any spaces.
PlaceholderA placeholder is the part of a format string between the {braces}.
PluralLocalizationFormatterFormats values according to culture-specific pluralization rules.
PluralRulesMaps two-letter ISO language codes to their pluralization rules. PluralRules are used by extensions like
TimeFormatter
and
PluralLocalizationFormatter
.
PoolingExceptionRepresents an Exception thrown by the pooling subsystem.
PropertiesSourceEvaluates a selector by reading the member of the same name through the Unity.Properties data model.
SByteVariableA IVariable that holds a single signed byte value.
SelectorRepresents a single selector in a Placeholder. E.g.: {selector0.selector1?.selector2}, while "." and "?." and "?[]" are operators.
ShortVariableA IVariable that holds a single short value.
SmartThis class holds a Smart.Default instance of a SmartFormatter. The default instance has all extensions registered. For optimized performance, create a SmartFormatter instance and register the particular extensions that are needed. Smart methods are not thread safe.
SmartExtensionsProvides extension methods that apply Smart String formatting to StringBuilder, TextWriter, and string.
SmartFormatterConstructs formatted strings by invoking each registered source and formatter extension.
SmartSettingsSmart settings to be applied for parsing and formatting. SmartSettings are used to initialize instances. Properties should be considered as 'init-only' like implemented in C# 9. Any changes after passing settings as argument to CTORs may not have effect, unless explicitly mentioned.
SmartStringsSettingsProject-wide Smart Strings settings. The active instance is included in player builds as a preloaded asset and exposes the default SmartStringsSettings.SmartFormatter used to format Smart Strings.
SourceThe base class for ISource extension classes.
StringOutputWraps a StringBuilder so it can be used for output.
StringSourceEvaluates a Selector with a
string
as ISelectorInfo.CurrentValue. Include this source for handling
string
and its extension methods.
StringVariableA IVariable that holds a single string value.
SubStringFormatterOutputs part of an input string.
TemplateFormatterRegisters reusable templates and applies them by name.
TextWriterOutputWraps a TextWriter so that it can be used for output.
TimeFormatterFormats time spans as human-readable text, such as 1 day 2 hours.
UIntVariableA IVariable that holds a single unsigned integer value.
ULongVariableA IVariable that holds a single unsigned long value.
UShortVariableA IVariable that holds a single unsigned short value.
Variable<T>Base class for all single source variables. Inherit from this class for storage for a single serialized source value that will send a value changed event when Variable<T>.Value is changed. This will trigger any localized string that is currently using the variable to update.
VariablesGroupAssetCollection of IVariable that can be used during formatting of a localized string.

Enums

Enum

Description

CaseSensitivityTypeOptions for whether strings are processed case-sensitively.
FormatErrorActionDetermines how format errors are handled.
ParseErrorActionDetermines how parsing errors are handled.
SelectorFilterTypeSets which characters a selector can contain.
TimeSpanFormatOptionsDetermines all options for time formatting. This one value actually contains 4 settings:
Abbreviate
/
AbbreviateOff``LessThan
/
LessThanOff``Truncate
 
Auto
/
Shortest
/
Fill
/
Full``Range
 
MilliSeconds
/
Seconds
/
Minutes
/
Hours
/
Days
/
Weeks
(Min / Max)

Interfaces

Interface

Description

IFormatterConverts an object to a string.
IFormatterLiteralExtractorExtracts the literal characters from a Format string
IFormattingExtensionsToggleLets a source stop formatter extensions from running for the placeholder it resolved.
IFormattingInfoContains all necessary info for formatting a value
IInitializerInitializes an ISource or IFormatter.
IMetadataVariableAdds support for querying the Metadata in a Smart String.
IOutputRepresents a destination for formatted text.
ISelectorInfoContains all the necessary information for evaluating a selector.
ISourceEvaluates a selector.
IVariableRepresents a variable that can be provided through a global VariablesGroupAsset or as a local variable through localized string instead of as a string format argument. A variable can be a single variable, in which case the value should be returned in IVariable.GetSourceValue or a class with multiple variables which can then be further extracted with additional string format arguments.
IVariableGroupProvides access to a collection of named IVariable values.
IVariableValueChangedProvides the ability to trigger an automatic update of a localized string when IVariableValueChanged.ValueChanged is invoked.