videogames development

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

Unity 3D Game Engine – Text Rotator

Unity 3D Game Engine – Text Rotator

How to create an easy to use Text-Rotator using Javascript Arrays

1. MAIN TOP MENU> GameObject> Create Other> GUIText

2. MAIN TOP MENU> GameObject> Create Empty> name it DialogueController, assign DialogueController.JS

DialogueController.JS:


#pragma strict

var character: GUITexture; 	// Assegnare in Inspector
var baloon: GUITexture; 	// Assegnare in Inspector
var baloonText: GUIText; 	// Assegnare in Inspector

    var transitionTime : int = 3; // da Inspector dare il tempo di transizione 
	var i : int = 0; // indice dell'array di frasi
	
	// array di frasi INIZIO #######################
	var sentences = new Array (); 
	sentences[0] = "Statement-1";
	sentences[1] = "Statement-2";
	sentences[2] = "Statement-3";
	sentences[3] = "Statement-4";
	// array di frasi FINE #########################


function Start () {

	// Dimensiono e posiziono gli elementi di interfaccia INIZIO ###############
	// lo faccio da codice per renderli responsivi basandomi sulla risoluzione video
	character.pixelInset = new Rect(0f, 0f, Screen.width/6, Screen.width/6); // la miniatura con la faccia del personaggio è 1/6 della risoluzione
	character.transform.position = Vector3(0, 0, 0); // posiziono la faccia in basso a sinistra
	
    baloon.pixelInset = new Rect(0f, 0f, Screen.width, Screen.width/6); // baloon
	baloon.transform.position = Vector3(0, 0, 0); 
	baloon.color = Color.blue; // colore del baloon
	baloon.color.a = 0.25f; // trasparenza del baloon
	// Dimensiono e posiziono gli elementi di interfaccia FINE #################	
	
}

function BaloonContent(){
	// NB: In anteprima può dare un flickering che scompare con la Build Finale
	baloonText.text = sentences[i].ToString();// scrivi la frase a video, convertire a stringa altrimenti verrà effettuato un - implicit downcast t0 string - con messaggio di avvertimento nella console
	yield WaitForSeconds (transitionTime); // attendi x secondi
	i = 1;
	yield WaitForSeconds (transitionTime);
	i = 2;
	yield WaitForSeconds (transitionTime);
	i = 3; // ultimo indice
}

function Update () {
BaloonContent(); // richiama scrittura testo	   
}// End Update()

4. Hierarchy> DRAG AND DROP GUIText over DialogueController.JS GUIText var

Done!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Text Rotator

Unity 3D Game Engine – Web Player – How to disable Right-Click context Menu

Unity 3D Game Engine – Web Player – How to disable Right-Click context Menu

How can you disable the default right-click context menu (i.e. shows “Fullscreen” option) from the application?

Super Easy!

MAIN TOP MENU> File> Build Settings> Player Settings> “Resolution and Presentation”> WebPlayer Template> “No Context Menu”

Into RIGHT COLUMN there are three options:

– Black background
– Default (white background)
– No Context Menu (no right click menu, white background)

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Web Player – How to disable Right-Click context Menu

Unity3D Game Engine – Get Objects with Find.name / FindWithTag / FindGameObjectsWithTag

Unity3D Game Engine – Get Objects with Find.name / FindWithTag / FindGameObjectsWithTag

Get Objects – Find.name

Restituisce un oggetto in base al nome che ha in Hierarchy

1. Create inside Hierarchy:

– parent ->’Arm’ (Cube) braccio
– child of Arm ->’Forearm’ (Cube) avambraccio
– child of Forearm ->’Hand’ (Cube) mano

– GameController(Empty Object) -> attach GameController.JS

2. GameController.JS:


#pragma strict

        // Devo associare i Gameobject a delle variabili
        // E' meglio private perchè non devo modificarla in Inspector
	private var hand : GameObject;
	private var arm : GameObject;

function Start () {
        // Hand non ha lo slash / all'inizio perchè ha un oggetto parent
	hand = GameObject.Find("Hand");
	// Arm ha lo slash / all'inizio perchè non ha un oggetto parent
	arm = GameObject.Find("/Arm");
}

function Update () {
        // Ruoto i singoli elementi
	hand.transform.Rotate(0, 100 * 10* Time.deltaTime, 0);
	arm.transform.Rotate(0, 100 * Time.deltaTime, 0);

}

Official docs:
GameObject.Find: http://docs.unity3d.com/ScriptReference/GameObject.Find.html

Get Objects – GameObject.FindWithTag

Restituisce SOLO L’ULTIMO OGGETTO a cui è stato assegnato un determinato tag.

1. Create inside Hierarchy:

– Hand1′ (Cube) -> Inspector assign Tag ‘MyHand’

– Hand2 (Cube) -> Inspector assign Tag ‘MyHand’

– GameController(Empty Object) -> attach GameController.JS

2. GameController.JS:


#pragma strict

// definisco la variabile per ottenere GameObject
private var hand : GameObject;

function Start () {
    // inserisco in una variabile l'oggetto con tag 'MyHand'
    // ritorna SOLO l'ultimo oggetto a cui è stato assegnato il tag
    hand =  GameObject.FindWithTag ("MyHand");
    
    // se l'oggetto con tag non esiste restituisce un messaggio di errore
    if (hand == null)
    {
        Debug.Log ("Cannot find 'MyHand'");
    }
}

function Update () {
        // Ruota
	hand.transform.Rotate(0, 100 * 10* Time.deltaTime, 0);

}

3. Play, ruota SOLO L’ULTIMO OGGETTO CON IL TAG

Official docs:
http://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html

Get Objects – GameObject.FindGameObjectsWithTag

Restituisce in un array di oggetti, TUTTI GLI OGGETTI a cui è stato assegnato un determinato tag.

1. Create inside Hierarchy:

– Hand1′ (Cube) -> Inspector assign Tag ‘MyHand’

– Hand2 (Cube) -> Inspector assign Tag ‘MyHand’

– GameController(Empty Object) -> attach GameController.JS

2. GameController.JS:


#pragma strict

// definisco la variabile per ottenere GameObject
// è un array di oggetti perchè potrebbero essere più di uno
var hands : GameObject[];

function Start () {
    // inserisco in una variabile l'oggetto con tag 'MyHand'
    // ritorna TUTTI gli oggetti a cui è stato assegnato il tag
    hands =  GameObject.FindGameObjectsWithTag ("MyHand");
}

function Update () {
    // Ruota gli oggetti contenuti nell'array hands[]
    hands[0].transform.Rotate(Vector3.back, 10 * Time.deltaTime);
    hands[1].transform.Rotate(Vector3.back, 10 * Time.deltaTime);
}

3. Play, ruotano TUTTI GLI OGGETTI CON IL TAG

Official docs:
http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D Game Engine – Get Objects with Find.name / FindWithTag / FindGameObjectsWithTag