Different way to format text string

Just a very simple way to (hopefully) improve workflow.

If you have to set a text value / string value that includes other variables instead of typing

string someString = "Hello my name is " + nameVar + " and I am level " + levelVar;

You can also use $ to include inline vars in brackets like this

string someString = $"Hello my name is {nameVar} and I am level {levelVar}";

Personally I really like doing it this way because you don’t have to open and close the string everytime.
Hope it helps someone :slight_smile:

3 Likes

Yes, I’m a big fan of this particular trick. In older versions of Unity, this wasn’t available (as Unity was several versions of C# behind the then current Microsoft standard). It’s still behind the standard, but not quite as far behind. Sam eventually mentions string interpolation in the fourth course in the series.

1 Like

This is one of the many reason I was glad Unity finally got updated with the C# version, or closer to it. There a so many useful features that enhance the ease / readability of our code.

Still a bit behind… we’re on a subset of 9 in the latest Unity.

That’s Unity 2021.
Roughly Speaking 2019 was C#7; 2020 was C#8; 2021 C#9.
Microsoft I think is still on 11 getting ready to move to 12.
I believe that Unity is planing on supporting .Net 6.0 soon.

1 Like

hello, i’m using the image fill for the percentage of life but i just can’t figure it out, i tried to follow the video but it only works for text, can you tell me a solution on how to do it? thanks

Check out our lecture on the Health Bar UI and the lecture following for a good breakdown of this.

Privacy & Terms