I’m not sure what part of the two responses (me and @Olmi ) in this thread you are not getting:
Olmi’s response with getters and setters is more “textbook correct” for the C# crowd but there’s no need to go that far. I just use public variables 99% of the time because I have the discipline to understand how my classes are supposed to be used. But Olmi is “more correct” than me, at the cost of more typing and complexity.
This is pretty key stuff and as a rough estimate I would guess that 90% of all Youtube Unity tutorials use this mechanism to “get at other things.” It’s nearly universal and certainly the simplest most-bulletproof way.
if you have 2 scripts, script1 and script2
script1 has a public int a;, important to have it public but if you don’t want to see it in the inspector use [HideInInspector] public int a;
you can either add script2 a public scrip1 myscript; line and in the inspector attach the gameobject containing script1 to it and use myscript.a = 5;
or you can use FindObjectOfType<script1>().a = 5; but this gets only 1 of those scripts, if there are more than 1 object with script1, you need to figure which one to change
You need a reference to the other script/class’s instance.
public class MyClass : MonoBehaviour
{
// Reference. Assigned using the Inspector by click-dragginga GameObject that contains an OtherClass component.
public OtherClass Other;
void Awake()
{
// Alternatively, find with code only. Better to have it stored somewhere so you don't have to use FindObjectOfType which is slow, and will only find the first instance.
Other = FindObjectOfType<OtherClass>();
// Alternatively, find on a GameObject you know the name of.
Other = GameObject.Find("GOName").GetComponent<OtherClass>();
}
void Start()
{
Other.Hello();
}
}
public class OtherClass : MonoBehaviour
{
public void Hello() => Debug.Log("Hello");
}
You need an instance of the other class to access it’s variables, but exactly how you get that is heavily dependent on the answer to the above question.