7

I want a script to run,

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

Fattie
  • 27,874
  • 70
  • 431
  • 719
Anopey
  • 351
  • 2
  • 3
  • 10
  • 1
    Can you just use the local file system to record this information? – erisco Apr 30 '16 at 15:42
  • I don't know, how can i do that? – Anopey Apr 30 '16 at 15:44
  • Check if the file `NotFirstRun` exists. If it does not exist then it is the first run, then create `NotFirstRun`. Running a second time will see that the `NotFirstRun` file exists. This is just a crude example. If you are persisting any other information locally already (such as game settings) then you can simply store a boolean with that mechanism. – erisco Apr 30 '16 at 15:48

4 Answers4

16

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
}
Programmer
  • 121,791
  • 22
  • 236
  • 328
2

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!

InDieTasten
  • 2,092
  • 1
  • 16
  • 24
djow-dl
  • 21
  • 2
1

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!");
        }
    }
}
Daniel
  • 11
  • 2
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Antoine Thiry Feb 14 '20 at 11:16
  • 1
    its my first post, sorry I will try to do better next time. – Daniel Feb 14 '20 at 14:54
1

It's simple

You can use Time.realtimeSinceStartup;

Example :

if(Time.realtimeSinceStartup < 10)
{ 
// first game opening
}else
{ 
// Welcome again
}

Reference : https://docs.unity3d.com/ScriptReference/Time-realtimeSinceStartup.html

Good luck!