Trouble changing a static string variable

In another script I change the value of my public static string variable named “input”

Controller.input = Controller.input.Replace(Controller.input, “hello”);

In the original script the value successfully changes to “hello” but when I try to change it back to " " in the original script it remains at “hello”.

Any ideas why this is happening?

‘Replace’ is maybe not what you want?

Just set the string directly:

Controller.input = "hello";
Controller.input = "";

That should work, assuming you’re not calling the code that sets it to “hello” (again) and overriding the change back.

Not sure why you’re using Replace if you are just replacing the entire string. But with what you posted, I’m not seeing anything that would be wrong. Ah, @methos5k was faster.

Just tried, but the value remains “hello”

Then you’ll need to make sure you aren’t changing it back somewhere or show us some code.

I found it the problem was I was going out of bounds in an array which I was feeding to the input value. Back to what you guys were saying earlier about not using replace, the only reason I use it is because strings are immutable no?

Replace replaces parts it finds in the string with your new value.

That, and assignment (and any other string operation) all return new string instances.

:slight_smile:

You cannot do this:

string myString = "Hello";
myString[0] = 'J';

Strings are immutable. But replace doesn’t get around that. It still returns a new string, same as reassignment does.

If you want a mutable string, you need to implement it yourself.

1 Like

Or use StringBuilder, but that can be overkill for simple text changes. :slight_smile:

1 Like