SharedInstance not updating through multiple scripts

Using a SharedInstance class:

public class Score {
	private static Score instance = null;
	public static Score SharedInstance {
		get {
			if (instance == null) {
				instance = new Score ();
			}
			return instance;
		}
	}
	public float score;
}

and editing the ‘score’ in the same script as that:

void Update () {
		score = score + rigidbody.velocity.x * scoreMultiplier;
}

is not updating in my other script:

public class ScoreTextScript : MonoBehaviour {

	float score = Score.SharedInstance.score;
	private Text scoreText;

	void Start () {
		scoreText = GetComponent<Text> ();
	}
	
	void Update () {
		scoreText.text = "Friction Energy [" + score.ToString() + "]";
		//Debug.Log (score);
	}
}

help with this would be greatly appreciated.

“float” is a value type. Value types are not reference types. When you do this line:

float score = Score.SharedInstance.score;

the value insode your Score class is copied into your local score variable. Of course changing the local variable won’t change the member variable of your Score class. You always have to use your accessor of your singleton when you want to change something inside that singleton instance.

You could cache the singleton in a local reference variable of type “Score”, however that is generally not recommended. Singletons provide a single access point which should be used in all cases.

So get rid of the local score variable and just do:

void Update () {
    scoreText.text = "Friction Energy [" + Score.SharedInstance.score.ToString() + "]";
}

Or if you want to additionally cache the singleton instance locally you can do:

private Score scoreScript = Score.SharedInstance;
void Update () {
    scoreText.text = "Friction Energy [" + scoreScript.score.ToString() + "]";
}

Though as i said this is not recommended.

I would have detailed the scripts, except that it failed to reach the server and I don’t want to repaste + edit all the scripts again. If anyone needs these, let me know somehow.