I have a function, for the simplicity and density of this question, lets say it is
void DoSomething (int number, string word) {
number = 10;
word = "hello";
}
when i do this, the int argument variable is changed, but the string argument never gets changed. I’ve tracked it down to this function. Its been happening to me a lot, but i usually find a work-around. Is it normal that strings don’t get changed from being parsed? if so… can someone explain why?
Either I don’t understand the question or the example is flawed.
Int is a value type and string acts like a value type in this respect so in this example you can’t change either of the ORIGINAL variables by passing them into a method like this.
void Awake() {
int myNumber = 1;
string myString = "goodbye";
DoSomething(myNumber, myString);
Debug.Log(myNumber + ", " + myString);
// Logs out "1, goodbye"
}
void DoSomething (int number, string word) {
number = 10;
word = "hello";
}
When you call a method with value type parameters, the value of the passed in variables gets copied and passed into the function, so inside the function you are changing just a copy of the original variables.
When you call a method with a reference type parameter such as GameObject, a reference to the original GameObject is passed into the function, so if you for example change the name of the GameObject, you’ll see the change wherever you have a reference to the same GameObject
String is actually a reference type but in this respect it acts like a value type.
Value type vs. reference type in C#