In their Roll-a-Ball project tutorial, Unity guys use ToString() method, to display text in their GUIText field.
countText.text = "Count: " + count.ToString();
yet in the SpaceShooter tutorial they write it without ToString();
void UpdateScore ()
scoreText.text = "Score: " + score;
That’s a bit confusing.
When should we use the ToString() method?
In what cases should we avoid it?
Space shooter tutorial
As said above: In your example, there is no difference.
For most types, especially the built in value-types,
"Score: " + score is the same as
"Score: " + score.ToString() This is because the default conversion operator for string calls ToString().
However, if the type you are using overloads that operator, results can differ:
It doesn’t make a difference. The second example implicitly calls the ToString() method using an implicit type cast. It doesn’t work for all types, but fundamentally, it’s just a shortcut to make your code neater - there is no actual difference between the two code samples you posted.
There is not much difference in its functioning, both does essentially the same thing. The added ToString() gives readability to you code. Easy to understand!
But one major difference is while using ToString() you have to be careful that you shouldn’t use it on a null reference!
If the class is created by you, then you can inherit it from IConvertible interface and have a custom control over ToString() method, inside ToString you can have functionalites that help you display the string the way you want. Imagine a Complex number (Eg obj - 3+4i) class created by you where ever you add it to string with either of the methods above! it would display in the above format.
Other than this there is no difference using it on a build it datatype! By doing “”+score you are indirectly calling score.ToString()
IMPORTANT DIFFERENCE one point I forgot to add is that ToString has a great advantage that it can take a string format as a parameter which is a nice way of customizing the output string! for example a
float x= 12.6789f; is there you can do something like this
x.ToString("00.00"); to get an output like
12.67 as result or
x.ToString("0%") to get
1268% as result.
It is strictly the same thing.
"Score:" is a string, and using the + operator requires two string operands. In this case, the right operand is not a string, so the method
ToString() will be called anyway on the right operand.
It is exactly the same thing when you write