- Home /
Why the variable don't change your value?
Hey guys,
There is a noob question but I don't find any place the answer.
The first script is just a variable and a method. The second is a method from another class.
What I don't understand is why the variable (first code) not change your value after the method. Thanks for the help. PS: I can't use static variables.
FIRST CODE
public int enter = 5;
private void Update()
{
if (Input.GetKeyDown(KeyCode.T))
meth.calculate(enter);
}
SECOND CODE
public static void calculate(int number)
{
number -= 1;
}
Answer by Ruri-Dev · Apr 28, 2017 at 05:12 PM
The method on the SECOND CODE is changing a local variable which scope extends to the method only. When you execute meth.calculate(enter)
you're passing enter
as a parameter and since an int
is a value type it's value is copied and then passed to the method. There are two simple fixes:
You change:
calculate(int number)
tocalculate(ref int number)
You change:
public static void calculate(int number) { number -= 1; }
to
public static int calculate(int number) { return number - 1; }
which is now returning an int, then call it on FIRST CODE as follows: enter = meth.calculate(enter);
Choose the one that suits you best.
That's answers all my questions. Thank you so much, you really helped me.
The sentiment in the answer is right but as @Bunny83 corrected me, I shall correct you :)
This does not happen because int is a value type. The same happens with reference types and it happens because method parameters are always passed by value unless you use the ref or out keywords.
If public int enter = 5;
was ins$$anonymous$$d public GameObject enter = new GameObject("A");
(a reference type) , the same would still happen: changing what GameObject number
references inside the method would not change what the field GameObject enter
references.