Reputation: 57
I'm using unity 5.5, and I met this problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WhatTheHell : MonoBehaviour
{
public static int testVal;
void Awake()
{
SetVal(testVal);
Debug.Log(testVal);
}
void SetVal(int val)
{
val = 10;
}
}
The debug result is 0 insted of 10. why?
Upvotes: 1
Views: 129
Reputation: 382
To avoid other mistakes of this type I would encourage you to read this: https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/stack.html the
Upvotes: 0
Reputation: 709
The problem is that int is a value type and not a reference type.
When you pass 'testVal' to 'SetVal()', it make a copy of the value of 'testVal' into 'val' just for the method scope.
If you use the keyword ref, 'val' argument will be handle as a reference type
void SetVal(ref int val)
SetVal(ref testVal);
More about value and reference types here : https://msdn.microsoft.com/en-us/library/9t0za5es.aspx
Upvotes: 2
Reputation: 1607
you can perform this operation as multiple ways by making Global variable , ref Keyword or simple return int from function. as describe
Global Variable
public static int testVal=0;
void Awake()
{
SetVal();
Debug.Log(testVal); // print 10
}
void SetVal()
{
testVal = 10;
}
ref Keyword
public static int testVal=0;
void Awake()
{
SetVal(ref testVal);
Debug.Log(testVal); // print 10
}
void SetVal(ref int testVal)
{
testVal = 10;
}
return int
public int testVal=0;
void Awake()
{
testVal = SetVal();
Debug.Log(testVal); // print 10
}
int SetVal()
{
return 10;
}
Upvotes: 3
Reputation: 29006
Here you are defining the testVal
as static
so it will be available in all methods inside the class(you can access them outside the class as well through the class name that is WhatTheHell.testVal
). So actually there is no need for passing the variable in this case.
Then you are passing the variable testVal
to the SetVal()
method as pass by value, so it will pass the value only not the actual variable. that is why the change is not reflected the actual variable.
The following code will work as you expected:
public static int testVal=0;
void Awake()
{
Debug.Log(testVal); // print 0
SetVal();
Debug.Log(testVal); // print 10
}
void SetVal()
{
testVal = 10;
}
For more detailed explanation and example you can take a look into the Story of Pass By Value and Pass By Reference in C# by Ehsan Sajjad.
Upvotes: 2