Home > Blockchain >  What is the default access modifier for a variable in Unity, and why?
What is the default access modifier for a variable in Unity, and why?

Time:12-13

This is a somewhat more complicated question than it might appear.

Every Unity video and tutorial that discusses access modifiers that I can find tells me that "private is the default access modifier for member variables in C#", but according to the C# documentation the default access modifier should be internal.

So, the question is, what is the true story of what's going on here? If I don't put an access modifier on a variable in a unity script it does act private, but what is Unity doing to make this happen!? Somehow I cannot find an explanation online.

See also this unanswered question on Unity Answers.

CodePudding user response:

I think you are confused by the scope here: The default access modifier for members (fields and methods) is private, while the default access modifier for classes and interfaces is internal. That's because classes cannot be declared private (that would mean they're only visible within themselves, which doesn't make sense). An exception are inner classes (classes within classes), but for these, separate default rules apply.

It's good style to always explicitly declare the access modifier for all objects.

  • Related