In this video we’ll see how to access a variable that is defined in a script from another script in Unity.
Procedure to read a variable that is in another Script step-by-step:
1. We start with 2 scripts, A and B. In the A script is the variable we want to read. In the B Script we are going to read the variable that is in A.
2. In the A script we make sure that the variable is declared as public, otherwise we will not be able to access it from a context outside of A.
3. In the B script we declare an A-type object and we must find the reference of that object. This will depend on where we are programming, in the case of Unity we will do it in the Start method and with the instruction FindObjectOfType.
4.To read the variable that is in the A Script from B, we use the reference that we define from A and with the dot operator we can access it and use it inside the B Script.
This other video may be useful: