How to read VARIABLES from other Scripts. Example in C# Unity


In this article we will see how to read variables that are defined in a script from a second script.

In the following video you can see how to use the variables of other scripts step by step.

Procedure for using variables from other scripts

1. Let 2 scripts A and B. In A Script is the variable we want to read. In B Script we will 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 an external context to A.

3. In B script we declare an A type object and 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 in the other A Script from B, we use the reference we define from A and with the dot operator we can access it and use it inside the B Script.

Leave a Comment

Your email address will not be published. Required fields are marked *