Search code examples
c#unity-game-enginegame-engine

Using static variable in different class in Unity


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?


Solution

  • 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;