How to only intialize new values on software update?

Viewed 67

I want to init some Variables when the Unity game open for the first time

I have tried this

private void Awake()
{
    if (PlayerPrefs.GetInt("Onfirst") == 0)
    {
        PlayerPrefs.SetInt("Onfirst", 1);
        for (int i = 0; i < CHbutton.Count; i++)
        {
            PlayerPrefs.SetInt("buyCH" + MenuNum.ToString() + i.ToString(), 0);
            PlayerPrefs.SetInt("selectCH" + MenuNum.ToString() + i.ToString(), 0);
        }
        PlayerPrefs.SetInt("buyCH" + MenuNum.ToString() + '0', 1);
        PlayerPrefs.SetInt("selectCH" + MenuNum.ToString() + '0', 1);
    }
}

I'm using such a thing in many classes, the problem is on software updates, if I want to add any init Variables like this I have to add this script again and leave the first one because of the new users,

explaining this issue see this line

private void Awake() // let's say a player open the game and this Script done
{
    if (PlayerPrefs.GetInt("Onfirst") == 0)
    {
        PlayerPrefs.SetInt("Onfirst", 1);
        PlayerPrefs.SetInt("firstUpdate", 1);
    }
}

on the new software update

private void Awake() 
{
    if (PlayerPrefs.GetInt("Onfirst") == 0)
    {
        PlayerPrefs.SetInt("Onfirst", 1);
        PlayerPrefs.SetInt("firstUpdate", 1);
        PlayerPrefs.SetInt("SecUpdate", 1);
    }
}

now when the player update the Game, he will never receive these changes, so to solve this

private void Awake() 
{
    if (PlayerPrefs.GetInt("Onfirst") == 0)
    {
        PlayerPrefs.SetInt("Onfirst", 1);
        PlayerPrefs.SetInt("firstUpdate", 1);
    }
    if (PlayerPrefs.GetInt("Onfirst2") == 0)
    {
        PlayerPrefs.SetInt("Onfirst2", 1);
        PlayerPrefs.SetInt("SecUpdate", 1);
    }
}

and so on

let's say I'm using about 10 Scripts like above(cannot be merged), after many updates, I can't handle all of these lines,

what I really want is something like init Script every software update, but without resetting values that already exist.

1 Answers

You can use HasKey to check if these variables have already been set. If they have already been set, just don't initialize them:

private void Awake() 
{
    // first update
    if (!PlayerPrefs.HasKey("firstUpdate")) 
    { 
        PlayerPrefs.SetInt("firstUpdate", 1); 
    } 

    // second update
    if (!PlayerPrefs.HasKey("secondUpdate")) 
    {
        PlayerPrefs.SetInt("secondUpdate", 1); 
    }
}
Related