Unity 3D Game Engine – Load Next Level

Unity 3D Game Engine – Load Next Level

Syntax:


// Load the level named "level2".
Application.LoadLevel ("level2");

// Load the level index 1, 
// you find this value inside Buil Settings> 'Scenes in Build'
Application.LoadLevel (1);    

To improve performance a big game is broken over many levels.
Inside Unity3D you can use Scenes to create levels.

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;

function Start () {
scores = 10;

}

// 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.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Load Next Level

JS Basics – Passing variables between functions attached to different GameObjects

JS Basics – Passing variables between functions attached to different GameObjects

Hierarchy:

– Cube -> attach CubeScript.js

– GameController (Empty GameObject), Inspector> Tag rollout ‘GameController’ -> attach GameController.JS

CubeScript.js


#pragma strict

// definisco la variabile per il punteggio
var scoreValue : int; 

// variabile privata, non visibile in Inspector, mi serve per ottenere il componente GameController
private var gameController : GameController; 

function Start ()
{
    // inserisco in una variabile l'oggetto con tag GameController
    var gameControllerObject : GameObject = GameObject.FindWithTag ("GameController");
    // se l'oggetto con tag GameController esiste lo inserisco in una variabile
    if (gameControllerObject != null)
    {
        gameController = gameControllerObject.GetComponent (GameController);
    }
    // se l'oggetto con tag GameController non esiste restituisce un messaggio di errore
    if (gameController == null)
    {
        Debug.Log ("Cannot find 'GameController' script");
    }
}

function Update () {
SendData();
}

function SendData() {
    yield WaitForSeconds (3); // aspetta 3 secondi
    scoreValue = 10;
    // invia scoreValue allo script taggato GameController -> funzione AddScore()
    gameController.AddScore (scoreValue);
    Destroy(gameObject); // distruggi l'oggetto corrente altrimenti l'invio di dati si ripete ad ogni frame

}

GameController.JS


#pragma strict

// contatore di punteggio, private perchè non vogliamo che sia modificabile da Inspector
private  var score : int;

function Start () {

}

function Update () {

}

function AddScore (newScoreValue : int) {
    // aggiorna score aggiungendo il valore newScoreValue
    // che gli viene inviato da CubeScript.js
    // alla riga:  - gameController.AddScore (scoreValue); -
    score += newScoreValue;
    Debug.Log(score);  
    
}

The final console result is: 10

Spiegazione:

1. CubeScript.js
a. cerca un GameObject con il tag GameController
b. se presente ottiene dall’oggetto GameController il componente GameController (che non è altro che GameController.JS)
c. invia a GameController.JS -> funzione ‘AddScore()’ la variabile ‘scoreValue’;

2. GameController.JS
a. riceve nella funzione ‘AddScore()’ la variabile ‘scoreValue’
b. assegna ‘scoreValue’ alla variabile ‘newScoreValue’
c. effettua i calcoli e visualizza in console il risultato finale.

By |Unity3D, Video Games Development|Commenti disabilitati su JS Basics – Passing variables between functions attached to different GameObjects

Unity 3D Game Engine – Play an Animation On Click

Unity 3D Game Engine – Play an Animation On Click

1. MAIN TOP MENU> GameObject> Create Other> Cube> Inspector> Reset

2. MAIN TOP MENU> Window> Animation
TOP LEFT of Animation Window> Drop Down Menu ‘Create New Clip’> create ‘Pulse.anim’

3. Select the Cube or others Game Object in the scene.
Non ha importanza cosa scelgo, l’oggetto sarà influenzato al solo scopo di creare le chiavi dell’animazione, NON SARA’ ASSEGNATO ALL’OGGETTO CHE USO IN QUESTO MOMENTO!

4. Animation Window> REC Button> Create your Keys…
Project> select the Animation Clip> Inspector> Wrap Mode> Loop / Once (una volta sola) etc…

Repeat point 2-3 to create ‘Rotate.anim’

5. Hierarchy> select the Cube> Inspector> ‘Add Component’> Miscellaneous> Animation
Ora e stato aggiunto un ‘COMPONENT Animation’

DRAG E DROP da Project:

-‘Rotate.anim’ sopra il primo slot Animation, questa sarà l’animazione di default!

-‘Pulse.anim’ sopra lo slot libero in ‘Animations’, è la lista di tutto gli slot di animazioone disponibili, per aumentarla basta variare il parametro ‘Size’

– Spuntare ‘Play Automatically’

– Cullin Type: Based On Renderers, in questo modo l’animazione sarà calcolata solo se l’oggetto verrà renderizzato.

6. Aggiungere al Cubo lo script OnClick.JS


#pragma strict

function Start () {
	animation.CrossFade("Rotate"); 
	 
}

function OnMouseDown ()
{
        // When you click over the object
        // start the animation
        animation.CrossFade("Pulse");        
}
  
function Update () {


}

L’animazione di default sarà ‘Rotate’ in loop infinito, poi al click del mouse sarà ciclata una volta ‘Pulse’

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Play an Animation On Click

Unity 3D Game Engine – Passing Data between Levels

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 :)

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Passing Data between Levels

Unity 3D Game Engine – Saving Data – Multiplatform

Unity 3D Game Engine – Saving Data – Multiplatform

How to save persistent data on disk.

It works on:
– Standalone MacOSX / Windows / LinuX / Windows StoreApps
– WindowsPhone8 / Android
– Web Player Windows / MacOSX

Syntax:

...
PlayerPrefs.SetInt("Player Score", score); // 1. Set name and assign variable
PlayerPrefs.Save();                        // 2. Save All 
...
oldScore = PlayerPrefs.GetInt("Player Score"); // Get saved data
...

Script reference: http://docs.unity3d.com/ScriptReference/PlayerPrefs.html

Let’s go on!

1. Create:

– GUIText, name it ‘OldScoreText’

– Empty Object, name it ‘GameController’, attach ‘GameController.js’


#pragma strict
  
    // Multiplatform saving Data script
    // Attach this script to a GameController
    
    // It works on:
    // - Standalone MacOSX / Windows / LinuX / Windows StoreApps
    // - WindowsPhone8 / Android
    // - Web Player Windows / MacOSX
      
// Hierarchy DRAG E DROP over var GUI Text in Inspector
var oldScoreText : GUIText;
// touch counter, private because the users is not be able to change this value
private  var score : int;
private  var oldScore : int;
 
  
function Start () {
        // The counter initial value is 0
        score = 0;
        // load old saved score data
        oldScore = PlayerPrefs.GetInt("Player Score");
} // END Start ------------------------------------------------------

function Update () {
    // refresh old score data
    oldScoreText.text = "Old Score : "  + oldScore;
} // END Update -----------------------------------------------------
 
function OnGUI()
{
  // Aumenta il valore score ad ogni click
  if (GUI.Button (Rect (10,10,150,100), "You clicked:" + score)) {
        score ++;      
  }
  // Save Data On Click START #####################################
  if (GUI.Button(Rect(200,10,200,50),"Save Data"))
  { 
    // setta un valore intero - SetInt - di nome 'Player Score' di valore 'score'
    PlayerPrefs.SetInt("Player Score", score); 
    // ottiene il vecchio valore salvato in precedenza - deve avere lo stesso nome del salvataggio precedente
    // se non esiste restituisce il valore 0 oppure ""
    
    // questa funzione mi serve per fare confronti tra il punteggio vecchio e quello nuovo
    // infatti viene fatto il refresh del punteggio ad ogni click sul bottone
    oldScore = PlayerPrefs.GetInt("Player Score");
 
    // salva il valore ottenuto dalla partita corrente 'Player Score'
    PlayerPrefs.Save(); 
  }
  // Save Data On Click END #####################################
} // END OnGUI ------------------------------------------------------------

2. Hierarchy> DRAG AND DROP GuiText over Inspector> GameController.js> oldScoreText var

3. Build a Web Player, run HTML page
a. click ‘YouClicked’ button, then click ‘Save Data’ button
b. close the HTML page and reopen, you can see that ‘Old Score’ is a persistent data

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Saving Data – Multiplatform