Fast & Non-Alloc String Builder for Unity
Runtime/Text/UString.cs
HeaderDoc
(c) 2024 Sator Imaging, Licensed under the MIT License https://github.com/sator-imaging/Unity-Fundamentals
One liner API designed to easily achieve fast & allocation-free string operation.
// basic usage
var text = UString.Concat("Value: ", intVal);
var text = UString.Concat("Value: ", intVal.ToCharSpan("D5"));
// ~~~~~~~~~~~~~~~~~ instant non-alloc formatter
// 'using' statement is required to use as StringBuilder alternative
using (var sb = UString.Rent())
{
sb.Append("Value: ");
sb.Append(intValue);
UString.NewLineChars = "\r\n";
sb.NewLine();
var (array, consumed) = sb.GetRawBuffer();
textMeshPro.SetCharArray(array, 0, consumed);
}
Technical Notes
Prevent Allocation on Formatting Enum Types
Install StrictEnum
and set preprocessor symbol STMG_USTRING_USE_STRICT_ENUM
.
(on Unity, symbol is automatically set)
Note that in .NET 8 or later version, StrictEnum
is not required.
Overriding Formatter
There is an ability to override formatter by setting Override***Formatter
.
Formatter Precedence for Non-Primitive Types
UString chooses applicable formatter in the following order.
Enum
IFormattable
Nullable<T>
ValueType
Object