0

I have the following code

public class Score : MonoBehaviour {

    private static int score;
    public int sc;

    void OnTriggerEnter2D(Collider2D col) {
        if (col.tag == "Ball") {
            score++;
            sc = score;
        }
    }

and this is the class I'm using to get the score from the class above

public class ScoreText : MonoBehaviour {

    Score s = new Score();
    int sc;

    void Update () {
        sc = s.sc;
    }
}

But for some reason, my sc variable in the class ScoreText is always 0. How can I fix that?

John
  • 15
  • 1
  • 3
  • Both answers are wrong. Do not use the `new` keyword to create instance of script that inherits from `MonoBehaviour`. See [this](https://stackoverflow.com/a/37399263/3785314) for more information. – Programmer Jul 13 '17 at 00:36

2 Answers2

0

You can get the value of a static variable with class.property

public class ScoreText : MonoBehaviour {

    int sc =0 ;

    void Update () {
        sc = Score.score;
    }
}

And change private static int score; for public static int score;

Eliuber
  • 48
  • 1
  • 8
0

Change private static int score; to public static int score; and call it like this: Score.score = 5;

If you want to use it as property, you can do the following:

private static int _score;

public int score {
   get{return _score;} 
   set{_score = value;}
}
Sean Stayns
  • 4,082
  • 5
  • 25
  • 35