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