How do I make a variable work in two scripts?

I am using a tutorial by Brackeys for Unity and have decided to change it a little by having the score be based on the number of obstacles you hit. I have the collision counter on the player and want the Text in the UI to display it. How do I have the variable from the Player also work in the Text?


Well, to have the text be able to update according to the value in your obstaclesHit variable (I’m guessing), you’d need a reference to the whole object/MonoBehavior that contains the variable. Or, alternatively, a reference to the Text object (which I like better at the moment not knowing the full context). I’d recommend something like this:

  1. In your manager script that holds your obstaclesHit variable, expose a class variable to the inspector so that we can drag in the UI Text object: public Text hitDisplay; or [SerializeField] private Text hitDisplay;.
  2. In the inspector, drag in the UI Text object into that variable spot of your manager script (or whatever the script is).
  3. Every time you update the obstaclesHit variable in your manager script now, if hitDisplay != null, set its text to perhaps the obstaclesHit value.

There are multiple ways to do this, but I feel that this may be the most standard way of doing it that isn’t too complicated. If you have any further questions, or this doesn’t work out for you, let me know!