How to reference a float variable in 2 different scripts

As the title suggests I want to reference and use a float variable in 2 different scripts at the same time without creating a new one in every script. Does anyone know how to do that? And is it possible? Im new at programming so I don’t know all the tricks yet :slight_smile: . Any help is appreciated.

What do you want to do with that variable? If it’s a score you want to increment from different objects you could for example do this:

public class ScoreManager
{
     int score = 0;
  
     public void AddScore(int score)
     {
          this.score += score;
     }
}

You can then access the AddScore() method from any class that knows the ScoreManager:

ScoreManager scoreManager;

void Start()
{
     scoreManager = FindObkectOfType<ScoreManager>();
}

void Update()
{
     scoreManager.AddScore(5); //adds 5 to the score every frame
}

Other things you could do:

  • Make score public (not advised because of encapsulation)
  • Make ScoreManager static, so every class can call it from anywhere

Same concept goes for every other class. Make a method that modifies the variable and then call that from the other class.

Hey! Thanks for your help in the other post. The float will be a power variable that I want to have over multiple scripts at the same time.

Although, I get what your saying. Thanks for your help.

Say you want to use this power variable in some scripts. The script (and variable) are on some object in the game. You can add a reference to them in the other scripts where you want access to it. Then just drag n drop the object with the variable you want into that slot in the inspector. Almost the same as the previous poster said, except that you needn’t include the ‘Find’ portion, because you’re dragging it there instead :slight_smile: