Adding two variables from two different scripts.

Hello, I am trying to figure out how to add two variables from two scripts.

So let’s say we have two scripts.


 public ScriptTwo scriptTwo;
 public float mainNumber;
 public Button click;
 public void Click()
 mainNumber += 1;

So everytime to you click the button, it adds 1 to the “mainNumber” variable.


 public float numberTwo;
 public Button click;
 public void Click()
 numberTwo += 1;

So now Button Two will do the same thing but add 1 per click to the “numberTwo” variable.

So back to ScriptOne, I want numberTwo to be added to mainNumber. Let’s say numberTwo is 3 and mainNumber is 3. The ending result would be 5.

I tried doing mainNumber = mainNumber + scriptTwo.numberTwo but the number would just go up really fast and constantly. Anyone have a solution to this? (Hoping this was as clear as possible).

Quick solution, may not be the best:

Define a static class with two static variables. Those variables can then be used in any script of yours. The variables are bound to the class itself, rather than to a class instance.

public static class StaticNumbers
     public static float mainNumber;
     public static float numberTwo;


Then simply access them in your script like:

public void Click()
  StaticNumbers.numberTwo += 1;

Finally, you can simply add them like this:

StaticNumbers.numberTwo + StaticNumbers.mainNumber

If you reset the scene/game, also remember to reset the static variables to their original value.

If you do a little searching on google or unity answers you will find multiple of these same questions already answered.

You have to get the script component of the gameobject if it is a monobehaviour like so:

var script = yourobject.GetComponent<YOURSCRIPTNAME>();
script.mainNumber = 5;

However if the script is not monobehaviour you will either have to make the script static so you can access it right away like:

ScriptName.mainNumber = 5;

or make a new instance if static is not an option like:

var script = new YOURSCRIPTNAME();

declare your variables as static.then you can change or access the value of one variable from another script

the number would just go up really fast?? Its not clear. Please elaborate more. If your add coding is in Update it will run again n again. It will increase your count very fast. So please explain bit more.