Home > Back-end >  How to change text dynamic in unity
How to change text dynamic in unity

Time:11-07

enter image description here enter image description here

at line 161,I want to insert my text in parameter t,but it won't change when i debug it.although the parameter tmp had alredy changed.

enter image description here

I want to change this Text in UI,when my parameter t changes.

CodePudding user response:

The string type in c# is immutable, therefore Insert returns a new string instead of modifying the current one.

Do:

t = t.text.Insert(0, tmp   "//n");

See also

CodePudding user response:

With respect to your specific issue, Insert is defined as:

public string Insert (int startIndex, string value);

and returns a new string. In C#, strings aren't modified, new strings are created. In this way, they act like a value type, even though they're a reference type. In other words, once a string is created, it is never modified - it's 'immutable'. So, you need to store your newly created string.

In cases like this, I like to use the string interpolation, as it allows me to get a slightly clearer representation of what the final string will look like.

var tmp = System.Text.Encoding.UTF8.GetString ( e.Message );
t.text = $"{tmp}\n{t.text}"; // Note that a newline is represented as \n

Or, if you add the System.Text namespace; you could reduce it down to:

using System.Text;
...
t.text = $"{Encoding.UTF8.GetString ( e.Message )}\n{t.text}";
  • Related