Unity 3D Game Engine – Passing Data between Levels

When Unity3D loads a new scene it destroys all old GameObjects and data, but with – DontDestroyOnLoad – a GameObject will survive (At first I was afraid I was petrified
Kept thinking I could never live without you by my side…)

Syntax:

// Make this game object and all its transform children
// survive when loading a new scene.
// Also the value of variables will survive
function Awake () {
	DontDestroyOnLoad (transform.gameObject);
}   

1. MAIN TOP MENU> File> New Scene, create 2 scenes: level1 and level2
2. Project window> DOUBLE CLICK over level1 to select the scene
3. MAIN TOP MENU> GameObject> Create Empty ‘GameController’> Inspector> ‘Add Component’> GameController.JS


#pragma strict

var scores : int;

        // Make this game object and all its transform children
	// survive when loading a new scene.
        // also the value of variables (scores = 20) will survive
	function Awake () {
		DontDestroyOnLoad (transform.gameObject);
	} // END Awake

function Start () {
scores = 10;

} // END Start

// On Click Counter START #########################
//This is the variable we are using to store the number of clicks
var clickCounter: int;
//This creates a button and adds +1 to clickCounter variable every 1 click
function OnGUI () {
    if (GUI.Button (Rect (10,10,150,100), "You clicked:" + clickCounter)) {
        clickCounter ++;        
    }
}
// On Click Counter END ###########################

function Update () {

   if (clickCounter > 10) {
    scores = 20;
    // Load the level named "level2".
	Application.LoadLevel (level2);       
    }

} // END Update



4. MAIN TOP MENU> File> Buil Settings> DRAG AND DROP level1 and level2 scenes over ‘Scenes in Build’ window
Add the scenes into Build or Application.LoadLevel (“level2”); will not work!

When you click 11 times over the GUI.Button, level2 will be loaded, GameController object + its variables data will survive :)