Access Modifiers VS public GameObject in C#

Hello Unity Community !

i write this post to ask about the best practice when i comes to access/modify variables from one Class to another in C#.
after watching/reading tutorials about C# programming in Unity, i strongly suspect that my way to do certain things are not optimal.

i completely ignored the Access Modifiers concept, when i had to access public variables from one Class to another.
http://unity3d.com/learn/tutorials/modules/beginner/scripting/variable-scope-and-access-modifiers

Access Modifiers:
Declaring an external Class and then instantiate using “new”:

public class Access : MonoBehaviour {

private AnotherClass myOtherClass;

void Start()
{
myOtherClass = new AnotherClass();
myOtherClass.variable = 101;
}
}

as i said i completely ignored that “access modifiers” concept when i developed that demo.
what i did, when i had to access and modify values of variables from one Class to another under the same GameObject was:
-to declare as public the var that has to be access from “outside”
-to use a GetComponent().variable

when i had to access and modify variables from one Class to another, and that another Class was under another GameObject:
-i declared a public GameObject which was “link” to the gameObject i wanted to access its Class (and variables)
-and used GameObject.GetComponent().variable

is it optimal?
Should i use Access Modifiers instead? and how do i decide when to use it?

really? no one has an opinion on that issue?

It’s an easy question with a huge, complicated answer, since the decision quickly crosses over into the territory of class design and dependency management :slight_smile:

But some basic rules of thumb:

  • Use public only for fields you want to modify in Unity’s inspector panel and method you want to call from another script
  • Unity’s special methods (Update(), OnGUI(), etc.) should be protected by default. That will disallow other scripts to call them (which is undesirable) but allow derived classes to call the methods in the base class (in case you decide to make them virtual, which Unity handles just fine)
  • Everything that’s only callable from the script should be private.

Your way to access other scripts in the same GameObject and in other GameObjects is the only way there is, access modifiers just make explicit what parts of the other script can be accessed and what parts the script keeps for itself.

To establish links to other game objects, I’ve created a small dependency injector which calls a method named “Inject()” in each script and creates/looks up whatever other scripts this Inject() method has as its arguments in a global GameObject named “services”. But that approach is probably not straightforward if you don’t have a programming background in Java or .NET :smile: