Check if it's the first time running the game?

Hi all!

Feel like I’m here way too often at the moment, but here’s today’s question!! :stuck_out_tongue:
I have a script that changes some in game variables at start based on when the game was LAST run. This is all working fantastically with the one exception that if it is the first time the player is starting the game, it will insta kill them and trap them in that state no matter how many times the game has been rebooted.

My method for getting around this was a first run check, an int that defaults to true but can be disabled by checking the playerprefs. If it’s first time true, it skips the game state changes, and if it’s false it runs through them all.

So my method of doing this is as follows:

void start ()
{
firstRun = PlayerPrefs.GetInt("savedFirstRun");
if firstRun = 0
{
int firstRun = 1;
}
else
Do lots of game save loading

}

So the logic is, if it’s the first run, change the variable in future to false for first run. If it’s already false, go to game loading.
However it spits out this error

Assets/DataMaster.cs(20,9): error CS0135: `firstRun' conflicts with a declaration in a child block

I’ve tried googling this and while I can take a guess what it means I don’t truly understand the issue or have any idea how to fix it. If someone could clue me in or provide a solution it would be much appreciated

Just place the variable OUTSIDE the functions/events, as a class variable

int firstRun = 0; // variable inside the class, but not inside a function.

void start ()
{
  firstRun = PlayerPrefs.GetInt("savedFirstRun") ;


if (firstRun == 0) // remember "==" for comparing, not "=" which assigns value
{
  firstRun = 1;
}
else
{ 
   //Do lots of game save loading

}

}

Instead, you should do this:

if(PlayerPrefs.HasKey(<OneOfYourKeys>))
{
       LoadDataMethod();
}

which doesn’t waste any space storing a 1 time use variable.

There is a very simple way of asking unity if the player is running the first time, you can even count how many times the player ran the game!

just do this:

if(PlayerPrefs.GetString("unity.player_session_count") == "1"){
    //Ur stuff here!
}

I used this in my script:

if(PlayerPrefs.GetString("unity.player_session_count") == "1")
    {
        if (balance == 0)
        {
            Console.Log("No balance found, adding 100$!");

            PlayerPrefs.SetInt("money", 100);
            balance = 100;
        }

        if (playerName == null || playerName == "")
        {
            Console.Log("No name found, opening register page!");
            registerPage.SetActive(true);
        }

    }

And it works perfectly fine!