Count the times a game has been launched

Hi everyone, I would like to save in PlayerPrefs the time my game has been launched by the user. Is there any function to do it ? Thank you very much.

There are many ways to do this,
here is a super simple method to keep check

using System;
using UnityEngine;

public class GameLaunchCounter : MonoBehaviour
{
 int launchCount;

 void Awake()
 {
 // Check For 'TimesLaunched', Set To 0 If Value Isnt Set (First Time Being Launched)
 launchCount = PlayerPrefs.GetInt ("TimesLaunched", 0);

 // After Grabbing 'TimesLaunched' we increment the value by 1
 launchCount = launchCount + 1;

 // Set 'TimesLaunched' To The Incremented Value
 PlayerPrefs.SetInt("TimesLaunched", launchCount);

 // Now I Would Destroy The Script Or Whatever You
 // Want To Do To Prevent It From Running Multiple
 // Times In One Launch Session
 Destroy (this);
 }
}
2 Likes
void Awake()
{
   IncrementLaunchCount();
}

void IncrementLaunchCount()
{
   // check if the key exists.
   // if so, add to count
   // if not, first time launched, add key
   if ( PlayerPrefs.HasKey( "LaunchCount" ) )
   {
     // get the current count
     int lc = PlayerPrefs.GetInt( "LaunchCount" );
     // increment the count
     lc += 1;
     // set to PlayerPrefs
     PlayerPrefs.SetInt( "LaunchCount", lc );
   }
   else
   {
     // if not, first time launched, add key
     PlayerPrefs.SetInt( "LaunchCount", 1 );
   }
}

EDIT : whoops, sorry 5vStudios, was typing this up when you posted :slight_smile:

Well, thank you very much guys ! :slight_smile:

Haha, nice, it seems we both program similarly

1 Like

Yes, what all the good guys above said… the only thing I would add is this, in order to make sure you don’t have typos in the key string:

const string s_LaunchCount = "LaunchCount";

Then make every use of SetInt and GetInt and HasKey use s_LaunchCount instead of yet another string literal.

That way a) you’re immune to typos in the key string, which would introduce odd confusing behavior, and b) you can easily change the key name in the future by changing a single location.

3 Likes

Thanks a lot @Kurt-Dekker ! :slight_smile:

This is already be done by UNITY! I recognized this when I first used “BG Tools - Player Prefs Editor”:
PlayerPrefs.GetString(“unity.player_session_count”)
Interesting to mention: PlayerPrefs.DeleteAll() will not reset this!

this works on Unity Standalone AND also on Mobile (at least as I can say on Android)!
(Unity 2019.4.15)

3 Likes

Today I learned.

Well, I think I’d rather just track such a simple thing myself so when debugging I can easily reset it.

Generally, here’s a more-robust example of simple persistent loading/saving values using PlayerPrefs:

https://pastebin.com/icJSq5zC

Useful for a relatively small number of simple values.

1 Like