Based on your statement
even though in C++, [global variables]
are not created inside a class
I think you are confusing global variables with member variables.
Example:
public class ExampleClass {
private int privateMemberVariable;
public int publicMemberVariable;
[SerializeField] private int privateMemberVariableExposedToUnity;
public static int public classLevelPublicVariable;
}
The first one privateMemberVariable
, is a completely normal member variable, a separate one existing for each instance of the class ExampleClass
. In C++ this would be in the private section of the class declaration.
The next one, publicMemberVariable
is the same as the private one (one separate variable per instance), except you can access it from other classes (and their functions). Not a good practice, try to avoid it, even though you see Unity examples use public all the time. That is because declaring a member variable public exposes it to the Inspector in the Unity Editor, but the better way is…
privateMemberVariableExposedToUnity
which is only accessible from ExampleClass
, but is still exposed due to the annotation [SerializeField]
.
Finally, there is classLevelPublicVariable
, which is a static variable, meaning that only one exists of it per class, accessible from all instances from this class (and from outside as well, because it is public). Unless you know what you are doing, don’t use static variables.
None of these variables are global, all of them are related to the class ExampleClass
, because C# is (mostly) object oriented language. Using these types of variables is not just good practice, it is the “only” way to store data between functions (let’s not get into weird ways).