We Are All Accustomed To +=
Whenever you wish to concatenate two strings in your project, at some point you probably ended up doing something like:
string myString += "myOtherString";
The reason? It is of the first things you are probably taught to be able to do while programming, and it’s super easy to keep using, especially if you need to make a really long string.
The only issue on the long run, is that if all the text in a project is generated this way, it might have an impact on game performance, WITHOUT BEING “DRAWN” in the scene. So you might want to take a look at it.
There Must Be A Better Way
Instead of the normal operation, you should do something like the following:
StringBuilder _sb; private void Awake() {_sb = new StringBuilder()} private void CleanStringBuilder() { _sb.Length = 0; _sb.Capacity = 0; ) public string Concatenate(string stringOne, string stringTwo) { CleanStringBuilder(); _sb.Append(stringOne); _sb.Append(stringTwo); return _sb.ToString(); }
Of course, this seems like a lot of work for a few rescued bytes here and there.
Which is why I suggest using the StringBuilderExtension class over at the Unity Tools Repository, to be able to do the following:
string myString = "Hello".Append(" beautiful", " sparkly", " world"); // Results in: "Hello beautiful sparkly world".So you don’t need to make **ANY** prep work involving StringBuilder for each class.
Get More Useful Tips On The GitHub Wiki
What you just read about was ONE of several unity tips that are available on the Unity Tips Wiki.
Please also note that the wiki is updated often, so make sure to check it out!
Read More Unity Tips!Interesting how we all grow used to the “dirty” implementations huh? Well, it is better to know that later over never.
This concludes today’s post.