how do scenes communicate?

Hi there - very noobish question - apologies if it has been asked elsewhere - not sure how to phrase it. I come from trad game coding, where I would have an overarching main.c file, that calls things like the menu, game and graphics code in a big loop. However in Unity, in my prototype 2D game I have a number of scenes. I can make one call the next scene in c# using Application.LoadLevel(“main game”); or similar. To get this I attached a simple c# script to the background sprite in the main menu. But if the new scene loads presumably the previous code fragment ends, and all new code and assets are loaded in. So how do I have the same overarching control of these scenes? I’m not even sure how to do simple things like transfer a score from the game scene to the menu scene to display the score you just got before the game ended.

Sorry again for basic nature of question! Any help much appreciated.

Cheers,

Robin.

I am new to unity coding but I think this is what you want. Click the syntax for documentation link.

Object.DontDestroyOnLoad

You can make static members to keep state between scenes if you like.

public class Main
{
    private static int someFancyNumber;
}

You may want to create a singleton. I recently watched one of the better tutorials I’ve seen on the subject but was unable to find it for you.

Also,

PlayerPrefs.Save();

PlayerPrefs allow you to set ints, floats and string values. Use it to save data that can be called up from any scene, and of course set in any scene.

Airship, theilade - thanks for your response. I’ve tried the (possibly naive) approach of making a cube outside the camera’s viewpoint and attaching a c# script to it. This will effectively become my main control loop - DontDestroyOnLoad does seem to work - I was able to click through various menu pages using the spacebar and the code persisted. Thanks very much for that! Should do the job I’m after.

Johnny Photon - thanks for the info - singletons are a good way to handle global variables in a c# project and I’ll certainly end up using them as the game grows. My main problem was working out where exactly to put the over-arching code that calls singletons and other classes - the equivalent of the main function in c and c++. Using any old object with DontDestroyOnLoad seems like it should do the trick.

Renman3000 - thanks for the extra info. I assume PlayerPrefs.Save() is for storing player progress to disk, so not quite what I’m after, although very handy to know, and I’ll doubtless end up using it.

Thanks again chaps

Cheers,

Robin.