- Home /
Doesn't exist in the current context?
I am working on a scorekeeping system. So far I have a goal on each side of the map. When the "ball" hits the opposing goal, I want the player's score to be shown on the screen.
I have 2 objects in the hierarchy. 1 being GoalP1 and the other being GoalP2. I created a text field and positioned it accordingly. I put this in my gameManager script.
public class GameManager : MonoBehaviour {
public Text scoreText;
public static int redScore = 0;
public static int blueScore = 0;
void Update(){
scoreText.text = redScore.ToString () + "|" + blueScore.ToString ();
}
}
And then I put this in the BallController script.
if (col.gameObject.name == "GoalP1") {
blueScore = blueScore + 1;
}
if (col.gameObject.name == "GoalP2") {
redScore = redScore + 1;
}
I am not entirely sure what I'm doing wrong but am getting the error that 'blueScore' does not exist in this context. I am a fairly new programmer, so bare with me please.
Anywho, thanks for the help! -DaniTheKid
Answer by daniel_alves_bra · Sep 26, 2017 at 03:45 AM
redScore and blueScore belong to the GameManager class. So, if you wanna call these attributes in another class you must put first the GameManager instance, and after that you call the atributes.
Ex: on the BallController you can do
public GameManager gameManager;
on the update method you do:
void Update(){
gameManager.blueScore = "something";
gameManager.redScore = "something";
}
Remember to drag the GameManager to your BallController script.
The two variables are declared static. So he doesn't need an reference to the instance of the class but can simply do:
Game$$anonymous$$anager.redScore
ins$$anonymous$$d of
redScore
Yeah, you are right.
I'm not a C# programmer but It is kinda strange for me to have a static attribute if the value isn't been serialized anywhere. I think a static variable would be more useful if it was created to declare constants...
Answer by Agent27765 · Sep 26, 2017 at 02:33 AM
I am a fairly new programmer to but I would like to take a try at this. I have a Coin System which I believe can possibly changed an implemented into yours. for my coin system I have CoinText.text = "Coins:" + Coin; Maybe you can do 2 different texts and maybe do like redText.text = "Red:" + redScore; blueText.Text = "Blue:" + blueScore;
PS: I don't know if this will help much as I too don't know much. But hopefully you found this useful.
Your answer
![](https://koobas.hobune.stream/wayback/20220612135637im_/https://answers.unity.com/themes/thub/images/avi.jpg)