PlayerPrefs do not store across scenes

Hi, I programmed a little mobile game where you play the same level over and over again to farm and sometimes you get an item when you finish the level. After completing the level the item should be activated in the inventory, but as soon as the scene is restarted, everything is back to the beginning.
This code is when you press the button to get the item.
Thanks in advance,
-JONAS Philippe

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


public class reward : MonoBehaviour
{
   public int itemReached;
 
    public GameObject Item;

    // Start is called before the first frame update
    void Start()
    {
        if (PlayerPrefs.GetInt("ItemON", 0) == 1)
        {
            Item.SetActive(true);
        }
/*
   if (itemReached == 1)
        {
            Item.SetActive(true);
        }
*/
    }

    // Update is called once per frame
    void Update()
    {
       
        itemReached = PlayerPrefs.GetInt("ItemON");

    }
    public void ButtonPress()
    {

        Save();
      
   
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
       
    }

    private void Save()
    {
        PlayerPrefs.SetInt("ItemON", 1);
        PlayerPrefs.Save();

    }
}

@jonph964

I have no idea what is not working in that code, but you don’t need to call PlayerPrefs each update frame, you only need to get the value from player prefs in Start, and save you data in OnDisable or when player presses some save button for example.

I don’t see where you do an Item.SetActive( false); Is that your problem?

Keep in mind PlayerPrefs are global so if you have two rewards, this won’t work. There is only one “ItemON” variable in PlayerPrefs.

Don’t do that…

void Update()
    {
      
        itemReached = PlayerPrefs.GetInt("ItemON");
    }

keep the Update cleaner

void Start()
    {
        //Kurt-Dekker is right
        Item.SetActive(false);
        itemReached = PlayerPrefs.GetInt("ItemON", 0);
        if (itemReached == 1)
        {
            Item.SetActive(true);
        }
    }

Like Kurt said, you have “ItemON” in the whole game…

1 Like