1
\$\begingroup\$

I have a list of stickers and when a player completes a level they get awarded a sticker which I save into PlayerPrefs. I want to be able to return the list of sprites saved into PlayerPrefs on the awards scene.

I have not been to loop and match the PlayerPrefs. I am not sure how to go about this.

public class StickerManager : MonoBehaviour
{
    public List<Sprite> stickers = new List<Sprite>();
    public List<Sprite> unlockedStickers = new List<Sprite>();

    public void UnlockSticker (int id)
    {
        PlayerPrefs.SetInt("sticker", id);
    }

    public List<Sprite> LoadUnlockedSticker ()
    {
        int i = 0;
        foreach (Sprite spri in stickers)
        {
            if (PlayerPrefs.GetInt("sticker", i) == stickers[i])
                unlockedStickers.Add(stickers[i]);

            i++;
        }

        return unlockedStickers;
    }
}
\$\endgroup\$
1
\$\begingroup\$

Each key in PlayerPrefs can store only one value, and the value has to be an integer, float, or string.

So when you do something like PlayerPrefs.SetInt("sticker", 5); it means "throw out whatever value you had been storing in the slot named "sticker" and replace it with the number 5.

If your stickers are always collected in a fixed order, then this can work - your PlayerPrefs value stores a count of stickers obtained so far, and you know every one with an index less than the current count has been unlocked.

If your stickers can be obtained in any order, then you need a different strategy. While you could store up to 32 independent sticker acquisitions as bitfield flags packed into a single integer, a simpler method would be to assign a distinct key to each sticker:

// This gives you a way to assign a serialized name for each sticker in the inspector.
// By not using the index or name of the sprite itself, this is more robust to changes.
[System.Serializable]
public struct StickerEntry {
    public string name;
    public Sprite sprite;

    // As the key, we'll add a prefix, to be sure this key doesn't collide with others we use.
    public string GetKey() {
        return string.Format("Sticker-{0}", name);
    }
}

public StickerEntry[] stickers;
public List<Sprite> unlockedStickers;

public void UnlockSticker(int id) {
    // A value of 1 means "unlocked".
    PlayerPrefs.SetInt(stickers[i].GetKey(), 1);
    unlockedStickers.Add(stickers[i].sprite);
}

public List<Sprite> LoadUnlockedStickers() {
    unlockedStickers.Clear();

    foreach(var sticker in stickers) {
        if(PlayerPrefs.GetInt(sticker.GetKey(), 0) > 0)
            unlockedStickers.Add(sticker.sprite);
    }

    return unlockedStickers;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.