Start a Script when the Game starts(not a scene)

Hey community,

I try to run a script when my game starts and hold this over the whole running. Eg. i have a startscreen which should only shown on the beginning of the game. After loading a few scenes and loading the first again the startscreen shouldnt be there. I tried it by setting a bool in a Playerpref. This works perfect in the Editor, but by building the game and running it, there is never shown the startscreen.(Need it for mobile use) Here is the way i did it:

	void Awake () {
		if (PlayerPrefs.GetInt ("Start") == 1) {
			// Do this by beginning the Game. In this example setting the camera
			cam.position = new Vector3(0,0,-700);
				} else {
			// Do this when the scene is loaded a secound,third... time. In this example setting the camera to another point
			cam.position = new Vector3(1920,0,-700);
				}
		PlayerPrefs.SetInt ("Start",0);
	}

	void OnApplicationQuit() {
		PlayerPrefs.SetInt ("Start",1);
	}

Is there another way to do this? I dont find a function like OnApplicationEnter() or somthing like this. To exclude missunderstandings it wouldnt help me to create a new scene, because I animated my camera. Last, Im using the new Beta Version : 4.6.0b17 .

Thanks for any help and this great community(really I love it :wink: )

Julian

1 Answer

1

There is just some issue with your logic. Try the code below:

void Awake () {
        if (PlayerPrefs.GetInt ("Start") == 1) {
            cam.position = new Vector3(0,0,-700);
                } else {
            cam.position = new Vector3(1920,0,-700);
                }

        // We set the value to 0 to make it so for each next time the scene is loaded it will be 0 and the else condition will execute
        PlayerPrefs.SetInt ("Start",0);
        // We also need to save these changes to PlayerPrefs in order for those changes to take effect
        PlayerPrefs.Save();
    }
 
    void OnApplicationQuit() {
        // We set the value to 1 at application quit to make it start at the beginning again at next time user opens the application
        PlayerPrefs.SetInt ("Start",1);
        // We also need to save these changes to PlayerPrefs in order for those changes to take effect
        PlayerPrefs.Save();
    }

Oh, thank you ;) I didnt know that there even exist a way to save the PlayerPrefs manually. Helped my a lot!