0

I'm trying to store value of an INT scoreValue that is in scrip "SCORE" in Unity game.

as for every level it will be different value, at the moment I'm doing separate function LEVEL1(), LEVEL2() etc. and store that value in layerPrefs.SetInt("scoreLVL1", Score.scoreValue); & layerPrefs.SetInt("scoreLVL2", Score.scoreValue); etc. etc.

but If I'm planning to have 100 levels, I would need to do 100 functions.

Is there simpler way to store all the values of each level in one function ?

I'm a beginner in Unity and at the moment can't get my head around it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public string nextLevel = "Level02";
    public int levelToUnlock = 2;
    public sceneFade sceneFader;
    public PauseScript pauseresume;

    public void level1()
    {
        pauseresume.levelCompletedmenu();

        if (PlayerPrefs.GetInt("levelReached") < levelToUnlock)
        {
            PlayerPrefs.SetInt("levelReached", levelToUnlock);
        }

        PlayerPrefs.SetInt("scoreLVL1", Score.scoreValue);
        PlayerPrefs.Save();
    }

    public void level2()
    {
        pauseresume.levelCompletedmenu();

        if (PlayerPrefs.GetInt("levelReached") < levelToUnlock)
        {
            PlayerPrefs.SetInt("levelReached", levelToUnlock);
        }

        PlayerPrefs.SetInt("scoreLVL2", Score.scoreValue);
        PlayerPrefs.Save();
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
Arek Marcjanik
  • 105
  • 1
  • 7

1 Answers1

1

Yes, what about

public void level(int level)
{
    pauseresume.levelCompletedmenu();

    if (PlayerPrefs.GetInt("levelReached") < levelToUnlock)
    {
        PlayerPrefs.SetInt("levelReached", levelToUnlock);
    }
    
    PlayerPrefs.SetInt($"scoreLVL{level}", Score.scoreValue);
    PlayerPrefs.Save();
}

In general I would not recommend to use the PlayerPrefs for storing user progress. Rather (encrypt and) write a file to Application.persistentDataPath

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • I see you not recommend playerPrefs, but How would I call that stored value in other script? int levelOneWonWithPoints = PlayerPrefs.GetInt("level1"); int levelTwoWonWithPoints = PlayerPrefs.GetInt("level2"); ?? – Arek Marcjanik Sep 02 '20 at 10:32
  • what about e.g. a `Dictionary levelToPoints` so you store one entry for each level and map it to the points ? E.g. reading `var secondLevelPoints = levelToPoints[2];` and writing `levelToPoints[2] = 500;`. Using e.g. [NewtonSoft .Net Json](https://www.newtonsoft.com/json) you can directly (de)serialize from and to [`Dictionary`](https://www.newtonsoft.com/json/help/html/SerializeDictionary.htm) – derHugo Sep 02 '20 at 10:48