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?