Victor Cash Victor Cash - 1 month ago 8
C# Question

Static var lost its value after exit a method

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?

Answer

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.

Comments