# How do I add a random number of points to my score stored in Player Preferences?

My problem is the value I get from Random.Range is not stored, but I get another value instead.

• In level 1 I press the "claim" button to store a randomly-chosen score

• In level 2 I retrieve the level 1 score using player preferences.

• When I press the "claim" button again in level 2 I want to add the new random score to the score from level 1.

How can I do this?

Here is the code I'm using currently:

playermanager.cs

void Start()
{
}

void FixedUpdate()
{
creditsText.text = PlayerPrefs.GetInt("score").ToString();
}

public void GetClaim()
{

Debug.Log("random.range" + Random.Range(20, 40));

}


Output:

• I've attempted to rephrase your question to improve the grammar. Please let me know if I've changed the meaning from what you intended, and we can make further edits to bring it back on-target. – DMGregory Jun 30 at 12:09

There are several problems with this code.

1. pointsAdd is serving as a total score, not an addition, so you should name it appropriately: totalScore

2. Since you're loading it from Player Prefs in each scene anyway, it does not need to be static.

3. FixedUpdate is not the correct time to update a text string. It might get called multiple times per frame, but your text can only be seen once per frame, so the extra setting is just producing unnecessary string garbage.

In fact, you only need to set your text when your score changes.

4. You are assigning a new value to your score with =, instead of adding to it with +=

5. You seem to be calling Random.Range twice as though you expect the same value each time. Random.Range will return a new randomly selected value each time you call it.

public class ScoreManager {

public Text creditsText;
int totalScore;

// Set the text whenever the score changes, and ONLY when the score changes.
void SetScore(int newScore, bool save = true) {
totalScore = newScore;
creditsText.text = totalScore.ToString();
if(save)
PlayerPrefs.SetInt("score", totalScore);
}

void Start() {
SetScore(PlayerPrefs.GetInt("score"), false);
}

public void GetClaim() {

Debug.LogFormat("Adding {0} points to the current score {1} to get {2}",