I want a script to run,
whenever my game in Unity is opened for the first time.
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
}
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!
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!");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With