Unity 3D Game Engine – Android – Save Data – Local

Unity 3D Game Engine – Android – Save Data – Local

How to save points, user preferences and other datas inside an android device.

IMPORTANT!!!

Unity> MAIN TOP MENU> File> Build Settings> Player Settings…> Other Settings> Configuration> Write Access> External (SD Card), this setup will create inside Android Device using Windows 7 -> Phone/Android/data/com.Company.LuceDigitale

It this equal the write inside AndroidManifest.xml ->

This scene is a simple Tap Counter, let me introduce instructions, briefly:
a. if you Tap over the objects in the scene, counter will increase.
b. if you tap over the button ‘Save Data’, counter value will be saved inside android device.

In the game we there are 2 counters (GUI Text):
1. the realtime player score text
2. the saved old score text

Inside Hierarchy create the game Objects:

– Sphere (GameObject)
– GUI Text (GameObject) – name it ‘Old Score Text’
– GUI Text (GameObject) – name it ‘Player Score Text’
– Main Camera, attach the ‘TapCounter.js’:

TapCounter.js


#pragma strict
 
    // Only ANDROID NOT PC NOT IOS
    // Attach this script to the Main Camera
     
// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreText : GUIText;
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;
 
// Ray Cast Setup
var speed : float = 4;
var hit = new RaycastHit();
 
function Start () {
        // The counter initial value is 0
        score = 0;
        scoreText.text = "No Touch:";
        // load old saved score data
        oldScore = PlayerPrefs.GetInt("Player Score");
}
 
function Update () {

	// refresh old score data
    oldScoreText.text = "Old Score : "  + oldScore;
 
    // se c'è un tocco Input.touchCount AND la fase del tocco è quella iniziale TouchPhase.Began
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {
    // traccia i raggi dalla Camera dal punto del tocco
    var ray = Camera.main.ScreenPointToRay (Input.GetTouch(0).position);
 
        // se raycast colpisce l'oggetto
        if (Physics.Raycast (ray, hit)) {
        // fai partire la funzione che incrementa il contatore
        UpdateScore ();
        }
 
    }
}
 
function UpdateScore () {
    // score var increment of +1
    score += 1;
    // scoreText in assigned inside Inspector on GUI Text
    // change .text property and write it on the display 
    scoreText.text = "Touched: "  + score;
}

// Save Data On Click START #####################################
function OnGUI()
{
  if (GUI.Button(Rect(10,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
	oldScore = PlayerPrefs.GetInt("Player Score");
	// salva il valore ottenuto dalla partita corrente 'Player Score'
	PlayerPrefs.Save();	
  }
}
// Save Data On Click END #####################################

Hierarchy> Main Camera> Inspector> TapCounter.js DRAG AND DROP:
‘Player Score Text’ (GUI Text) over var ‘score Text’
‘Old Score Text’ (GUI Text) over var ‘Old Score Text’

For italian people:

Notare


if (GUI.Button(Rect(10,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
	oldScore = PlayerPrefs.GetInt("Player Score");
	// salva il valore ottenuto dalla partita corrente 'Player Score'
	PlayerPrefs.Save();	
  }

Come funziona?

0. IMPORTANTE: per abilitare l’app alla scrittura su SD seguire la seguente procedura:
Unity> MAIN TOP MENU> File> Build Settings> Player Settings…> Other Settings> Configuration> Write Access> External (SD Card)

questo creerà all’interno del dispositivo Android la cartella (vista da Win 7)
-> Phone/Android/data/com.Company.LuceDigitale

Equivale di fatto in un progetto Android a scrivere su AndroidManifest.xml
->

1. PlayerPrefs.SetInt(“Player Score”, score);
-> Imposta in RAM (non viene ancora scritto nulla), un valore intero ‘Player Score’, del valore ‘score’ che è appunto un numero intero

2. oldScore = PlayerPrefs.GetInt(“Player Score”);
-> Ottiene il vecchio valore salvato di ‘Player Score’ se presente, se non esiste restituisce 0 oppure “”
Questo passaggio è utile se è necessario confrontare i vecchi valori con i nuovi, per stabilire ad esempio una classifica o se ho superato un check point.

3. PlayerPrefs.Save();
-> Salva su SD i valori impostati dal comando del punto 1.

Per testare avviare l’app sul dispositivo Android, tocco ripetuto sull’oggetto in scena, tocco sul bottone per salvare il punteggio attuale. Spegne il dispositivo, riavviare e ricaricare l’app, il valore di ‘Old Score Text’ dovrebbe essere quello salvato in precedenza.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Save Data – Local

Unity 3D – Android – Native Microphone – JavaScript

Unity 3D – Android – Native Microphone – JavaScript

How to access Android Microphone.

Record and Play

Hierarchy> Main camera> Inspector> Add Component

– ‘Audio Listener’

– ‘Audio Source’ setup:
– ‘Mute ‘ -> uncheck
– ‘Play On Awake’ -> uncheck
– ‘Loop’ -> uncheck

– ‘GetAudio.js’


#pragma strict

function Start() {
}

function OnGUI()
{
  if (GUI.Button(Rect(10,10,60,50),"Record"))
  { 
    //static function Start(deviceName: string, loop: bool, lengthSec: int, frequency: int)
    audio.clip= Microphone.Start ( null, false, 3, 44100 ); 
  }
  if (GUI.Button(Rect(10,70,60,50),"Play"))
  { 
    // play audio clip you have just recorded
    audio.Play();
  }
}

How does it work?

1. if you will touch GUI.Button(Rect(10,10,60,50),”Record”
2. it records an audio clip of 3 seconds, ONLY one time, no loop (static function loop: bool -> false)

3. if you will touch GUI.Button(Rect(10,70,60,50),”Play”
4. it plays the audio clip you have just recorded, ONLY one time, no loop, because into Inspector>’Audio Source’ component is set to ‘Loop’ -> uncheck

Record – > Effects -> Play

Super Easy! You need only attach audio filters components to ‘Audio Source’.

Hierarchy> Main Camera> Inspector> ‘Add Component’> Audio> Audio Echo Filter, setup the filter

Inside Hierarchy you will see:

Main Camera>

– ‘Audio Listener’

– ‘Audio Source’ setup:
– ‘Mute ‘ -> uncheck
– ‘Play On Awake’ -> uncheck
– ‘Loop’ -> uncheck

– ‘Audio Echo Filter’

– ‘GetAudio.js’


#pragma strict

function Start() {
}

function OnGUI()
{
  if (GUI.Button(Rect(10,10,60,50),"Record"))
  { 
    //static function Start(deviceName: string, loop: bool, lengthSec: int, frequency: int)
    audio.clip= Microphone.Start ( null, false, 3, 44100 ); 
  }
  if (GUI.Button(Rect(10,70,60,50),"Play"))
  { 
    // play audio clip you have just recorded
    audio.Play();
  }
}

Record -> Chipmunks Voice -> Play

Hierarchy> Main camera> Inspector> Add Component

– ‘Audio Listener’

– ‘Audio Source’ setup:
– ‘Mute ‘ -> uncheck
– ‘Play On Awake’ -> uncheck
– ‘Loop’ -> uncheck
– ‘Pitch’ -> 1.58

– ‘GetAudio.js’

Record -> Satan Voice -> Play

Hierarchy> Main camera> Inspector> Add Component

– ‘Audio Listener’

– ‘Audio Source’ setup:
– ‘Mute ‘ -> uncheck
– ‘Play On Awake’ -> uncheck
– ‘Loop’ -> uncheck
– ‘Pitch’ -> 0.69

– ‘Audio Echo Filter’

– ‘GetAudio.js’

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Android – Native Microphone – JavaScript

Unity 3D Game Engine – Android – Native Camera Access

Unity 3D Game Engine – Android – Native Camera Access

Inside Hierarchy create the scene with:

1. Main Camera

2. Plane in front of the Camera, attach the script ‘GetcameraImg.js’

GetcameraImg.js


// Starts the default camera and assigns the texture to the current renderer
function Start () {
	var webcamTexture : WebCamTexture = WebCamTexture(); // assign the webcam source to var
	renderer.material.mainTexture = webcamTexture;       // render over material texture webcam source
	webcamTexture.Play();	                             // Play the webcam		
}

function Update () {
   
}

3. You can flip, mirror, rotate the 3D Plane to flip, mirror, rotate the webcam texture!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Native Camera Access

Unity 3D Game Engine – Get Screenshot – Android

Unity 3D Game Engine – Get Screenshot – Android

How to get a in-game Screenshot with Unity 3D – UNTESTED

IMPORTANT!!!

Unity> MAIN TOP MENU> File> Build Settings> Player Settings…> Other Settings> Configuration> Write Access> External (SD Card), this setup will create inside Android Device using Windows 7 -> Phone/Android/data/com.Company.LuceDigitale

It this equal the write inside AndroidManifest.xml ->

Method 1

Application.CaptureScreenshot

NOTICE: CaptureScreenshot is asynchronous. This is because capturing and saving the screen can take awhile.

Inside Hierarchy create a structure with:

1. Some Objects

2. Main Camera, attach the script ‘GetScreenShot.js’

GetScreenShot.js


#pragma strict

// For Android Devices ONLY
// Attach this script to Main Camera

// File> Build Settings> Player Settings...> Other Settings> Configuration> Write Access> External (SD Card),
// this setup will create inside Android Device using Windows 7 -> Phone/Android/data/com.Company.LuceDigitale
// It this equal the write inside AndroidManifest.xml ->  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

var scoreTextX : GUIText;
var localize   : String;

function Start() {
}

function OnGUI()
{
  if (GUI.Button(Rect(10,10,200,50),"Capture Screenshot"))
  { 
    // debug data path
    localize = Application.persistentDataPath;
    scoreTextX.text = localize;
    // it writes:  /storage/sdcard0/Android/data/<bundle id>/files folder
    
    // We should only read the screen buffer after rendering is complete
    yield WaitForEndOfFrame();
    
    // Application.dataPath DOES NOT have write permission on Android, you need Application.persistentDataPath
    // static function CaptureScreenshot(filename: string, superSize: int = 0): void;
    Application.CaptureScreenshot("Screenshot.png");
    // the file will be saved on: /storage/sdcard0/Android/data/<bundle id>/files folder
  }
}

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Get Screenshot – Android

How to get GPS coordinates in Unity 3D

How to get GPS coordinates in Unity 3D

Inside Hierarchy create a scene with:

1. GUI Texture
2. Main Camera, attach the script ‘GetGpsCoord.js’

GetGpsCoord.js


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;
var localize   : String;

function Start () {
        // First, check if user has location service enabled
        if (!Input.location.isEnabledByUser)
            return;
        // Start service before querying location
        Input.location.Start ();
        // Wait until service initializes
        var maxWait : int = 20;
        while (Input.location.status
               == LocationServiceStatus.Initializing && maxWait > 0) {
            yield WaitForSeconds (1);
            maxWait--;
        }
        // Service didn't initialize in 20 seconds
        if (maxWait < 1) {
            print ("Timed out");
            return;
        }
        // Connection has failed
        if (Input.location.status == LocationServiceStatus.Failed) {
            print ("Unable to determine device location");
            return;
        }
        // Access granted and location value could be retrieved
        else {
        localize = Input.location.lastData.latitude + " " +
                   Input.location.lastData.longitude + " " +
                   Input.location.lastData.altitude + " " +
                   Input.location.lastData.horizontalAccuracy + " " +
                   Input.location.lastData.timestamp;
                                      
                   scoreTextX.text = "GPS coordinates "+localize;
        }
        // Stop service if there is no need to query location updates continuously
        Input.location.Stop ();
    }

Hierarchy> Main Camera> GetGpsCoord.js> DRAG AND DROP GUI Texture over var scoreTextX

The final result is:

45.04529 -> latitude
11.72339 -> longitude
0 -> altitude
2099 -> horizontalAccuracy
1396651772.795 -> timestamp

By |Unity3D, Video Games Development|Commenti disabilitati su How to get GPS coordinates in Unity 3D