Can unity automatically release static variables?

public sealed class Test : MonoBehaviour
{
    private static int _id = 10;
    private static Dictionary<int, string> _dic = new Dictionary<int, string>();
}

Let’s write it like this , Mount the Test script to the Gameobject , do these two variables( _id , _dic ) automatically free up memory when the GameObject is destroyed by another script, or when you jump from the current scene to another?

I remember that C# static variables will take up memory until the program is closed, thank you for your answer.

Why would they? Static variables are not tied to any specific instance, so why would destroying the instance have any effect?

4 Likes

Static values only reset during a domain reload, and sit in memory until the application closes. Beyond those points, you are responsible for managing them.

2 Likes

The others have already said it, but given your description it seems you have the wrong idea about static variables in general. You don’t need to create an instance of that class in order to use the static variables. Static variables or methods belong to the class itself, not to an instance of a class.

You made your two variables private, so they can only be accessed from a scope that is tied to this class (that means either static or instance methods of that class).

Just assuming for a moment that your static variables would be public, you could do this in any other class without ever creating an instance of your Test class

Test._dic.Add(42,"The meaning of life");
1 Like