Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Unity, how to tell if it's the first time a game is being opened?

Tags:

c#

unity3d

unity5

I want a script to run,

whenever my game in Unity is opened for the first time.

like image 302
Anopey Avatar asked Apr 30 '16 15:04

Anopey


3 Answers

Use PlayerPrefs. Check if key exist. If the key does not exist, return default value 1 and that is first time opening. Also, If this is first time opening set that key to 0 so that if will never return 1 again. So any value that is not 1 means that it is not the first time opening. In this example we can call the key FIRSTTIMEOPENING.

if (PlayerPrefs.GetInt("FIRSTTIMEOPENING", 1) == 1)
{
    Debug.Log("First Time Opening");

    //Set first time opening to false
    PlayerPrefs.SetInt("FIRSTTIMEOPENING", 0);

    //Do your stuff here

}
else
{
    Debug.Log("NOT First Time Opening");

    //Do your stuff here
}
like image 65
Programmer Avatar answered Nov 09 '22 07:11

Programmer


It's simple.

You can use PlayerPrefs.HasKey

Example:

if(!PlayerPrefs.HasKey("firstTime")) //return true if the key exist
{
   print("First time in the game.");
   PlayerPrefs.SetInt("firstTime", 0); //to save a key with a value 0
   //then came into being for the next time
}
else
{
   print("It is not the first time in the game.");
  //because the key "firstTime"
}

Reference https://docs.unity3d.com/ScriptReference/PlayerPrefs.HasKey.html

Good luck!

like image 27
djow-dl Avatar answered Nov 09 '22 07:11

djow-dl


My code:

public class LoadSaveManager : MonoBehaviour
{
    public int IsFirst; 

    void Start ()
    {
        IsFirst = PlayerPrefs.GetInt("IsFirst") ;
        if (IsFirst == 0) 
        {
            //Do stuff on the first time
            Debug.Log("first run");
            PlayerPrefs.SetInt("IsFirst", 1);
        } else { 
            //Do stuff other times
            Debug.Log("welcome again!");
        }
    }
}
like image 39
Daniel Avatar answered Nov 09 '22 08:11

Daniel