Access Variables from another C# script on same object?

I have two scripts, a countdown script and a generator script.

The generator has a public int score value and CorrectMatches value, and in the countdown script I want to modify the score based on how much time is remaining…

Generator.cs

public int correctMatches = 0;
public int score = 0;

Countdown.cs

// if (correctMatches > 2 )
// score = score * remainingTime;

So what’s the correct way to reference variables from the Generator.cs from within the Countdown.cs script?? It’s confusing… (remainingTime is a variable from Countdown.cs, so it’s fine)

And both these scripts are attached to the Main Camera. Thanks for any help!!!

One of the most asked questions on UA. The short answer is:

gameObject.GetComponent<Generator>().correctMatches;

In reality, if you are going to be doing it every frame:

private Generator gen;

void Start() {
    gen = gameObject.GetComponent<Generator>();
}

Then you can just use ‘gen.correctMatches’.

References:

http://unitygems.com/script-interaction1/

http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

Hi,

You have to create a variable in your Countdown.cs script:

private Generator myScriptName;

void Start(){

  myScriptName = gameObject.GetComponent("Generator") As Generator;

}

// if (correctMatches > 2 )
// myScriptName.score = myScriptName.score * remainingTime;

regards