C# - Access the Same Variable in Two Scripts
I have int score = 0;
in a script named Done_GameController.cs
. Then, I have code that changes the value of score
:
public void AddScore (int newScoreValue)
{
score += newScoreValue;
UpdateScore ();
}
void UpdateScore ()
{
scoreText.text = "Score: " + score * 10;
}
void SecondScore ()
{
score + 10;
}
Then, I have a script named Done_DestroyByContact.cs
which basically controls the player's death. Here's the code:
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
gameController.GameOver();
?????
}
I'm not sure what to put where the ?????
is, but I want it to be something like this:
Done_GameController.GetComponent.score;
score - 200;
In other words, I want to change score to score - 200
. How can I do this?
Answer by ionside · Feb 06, 2017 at 03:44 AM
hey @Nathansmash You could either define score as a static variable static int score = 0; (makes it a global variable, kinda scary)
or create Accessors - getter/setter (which is better)
public int Score{
get {return score;}
set {score = value;}
};
this will let you 'set' and 'get' the value of score from other scripts.
@ionside Are you sure you don't have to specify the file you're getting it from? Also, is the code above for Done_GameController.cs
or Done_DestroyByContact.cs
?
$$anonymous$$y apologies, @Nathansmash . Yes you should specify the script you're referencing from. I would add the above code to Done_GameController.cs Check out https://unity3d.com/learn/tutorials/topics/scripting/properties as an example
@ionside How would you change the value of score
in Done_DestroyByContact
and have it effect Done_GameController
?
Your answer
Follow this Question
Related Questions
Problem while using several tags in a OnTriggerEnter (Collider other) 0 Answers
Use of unassigned local variable 'startPos' " & " Use of unassigned local variable 'endPos' 1 Answer
Animator Parameter not linking to script variable 0 Answers
Help with converting small pseudo script to C# please? 0 Answers
How to change text based on the value of a scrollbar? 1 Answer