code snippets

Unity 3D – AAA Sound Manager – JavaScript

Unity 3D – AAA Sound Manager – JavaScript

Best practices for playing a lot of audio.

Create a Unity 3D Project with:

1. Main Camera

2. Cube, attach the script ‘GetAudioCenter.js’:


#pragma strict

// private to hide in inspector: nome dello script da prelevare
private var audioCenter : AudioCenterScript;

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

function Update () {
}


function OnMouseDown ()
{
        // When you click over the object
        Debug.Log('clicked'); // Debug Code, remove in the end
        // invia a AudioCenterScript.js, alla funzione play sound il suono da utilizzare
        var trackValue : int = 1;
        audioCenter.PlayTrack (trackValue);
}

3. Empty Object> Inspector:

a. name it ‘AudioCenter’
b. tag it ‘AudioCenter’
c. Transform> Reset, it puts the object at 0,0,0
d. Add Component> Audio Souce> uncheck ‘Play On Awake’ -> VERY IMPORTANT
e. attach the script ‘AudioCenterScript.js’:


#pragma strict

// assign the audio clips into Inspector START ###########
// NOTICE: the best practice is to use understandable names
// IMPORTANT: you can organize your audio clips into separate AudioCenter, example: dance, classic etc...
var bigJump: AudioClip;        // track 1
var smallJump: AudioClip;      // track 2
var miniJump: AudioClip;       // track 3
var outWaterJump: AudioClip;   // track 4
// assign the audio clips into Inspector END #############

function Start () {

}

function Update () {

}

function PlayTrack (trackValue : int) {
if (trackValue == 1)
    {
        // play the track 1, volume 0-1
        // here you can setup via code volume of the track or SFX
        audio.PlayOneShot(bigJump, 1);
    }
    // if (trackValue == 2) -> it will play track 2 and so on...
}

Inspector assign your SFX (wav or mp3) to vars

4. Play! If you click over the cube, the sfx of AudioCenter(Empty Object)>AudioCenterScript.js plays.

Spiegazioni in italiano:

Immaginiamo di dover realizzare un platform come Super Mario per Wii che contiene centinaia di effetti sonori, differenti per ogni nemico che incontriamo in questo platform. E’impensabile poter gestire una tale quantità di effetti aggiungendoli semplicemente ai singoli prefab sparsi per i livelli, magari alcuni di questi suoni potrebbero essere pure condivisi da diversi oggetti o scaturire in azioni e reazioni varie sparse per decine di mondi virtuali giocabili.

La soluzione è quella di creare un solo oggetto vuoto che ha lo scopo di:

– contenere la lista completa dei suoni all’interno di variabili
– gestirne il volume tramite la funzione di Unity3D, PlayOneShot()
– avere un’unica ‘Audio Souce’ in game. La funzione PlayOneShot() ci permetterà di utilizzare anche più suoni nello stesso istante, sovrapponendoli.

Come funziona il nostro codice?

1. GetAudioCenter.js
a. Rileva l’esistenza dell’oggetto con il tag ‘AudioCenter’
b. Se positiva ottiene lo script ‘AudioCenterScript.js’ attaccato all’oggetto ‘AudioCenter’
c. Invia a AudioCenterScript.js> funzione PlayTrack() un valore ID della traccia
b. Rileva il click del mouse all’oggetto al cui è applicato come componente

2. AudioCenterScript.js
a. Incorpora nelle variabili le tracce sonore
b. Riceve all’interno della funzione PlayTrack(), la variabile trackValue
c. In base a trackValue viene eseguita una specifica traccia utilizzando il componente ‘Audio Source’. Questo ha di default disattivato il parametro ‘Play On Awake’, quindi è muto finchè non arriva l’input di GetAudioCenter.js

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – AAA Sound Manager – JavaScript

Get Component – Script from Another Object

Get Component – Script from Another Object

Create a new scene with:

1. Camera

2. GUI Text

3. Cube, attach ‘CubeScript.js’


#pragma strict

// private per nasconderla in Inspector: nome dello script da prelevare
private var gameController : GameControllerScript;

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

function Update () {
}


function OnMouseDown ()
{
        // When you click over the object
        Debug.Log('clicked'); // Debug Code, remove in the end
        // invia a GameControllerScript.js, alla funzione TextUpdate() la variabile myNewTextValue
        var myNewTextValue : int = 2;
        gameController.TextUpdate (myNewTextValue);
}

4. Empty Object:

a. name it ‘GameController’
b. tag it ‘GameController’
c. Transform> Reset, it resets the position at 0,0,0
d. attach ‘GameControllerScript.js’


#pragma strict

var mytext : GUIText; // Assign it in Inspector
private var myTextValue : int; // hide it in Inspector, we want drive it only via code!

function Start () {
// give them an initial value when the game starts
mytext.text = "First text"; 
myTextValue = 1;
}

function Update () {
}


function TextUpdate (myNewTextValue : int) {
if (myNewTextValue == 2)
    {
        // play the track 1, volume 0-1
        mytext.text = "Second text";
    }
    // if (trackValue == 2) -> it will play track 2 and so on...
}

e. Inspector> ‘GameControllerScript.js’ assign the GUIText into var slot

5. Play, when you click over the Cube the GuiText changes!

For italian people: Come funziona?

1. ‘CubeScript.js’ controlla l’esistenza di GameController(oggetto)
2. se esiste ottiene da GameController(oggetto) il componente ‘GameControllerScript.js’
3. invia al click del mouse a GameControllerScript.js> funzione TextUpdate() un valore
4. ‘GameControllerScript.js’ riceve questo valore e cambia la stringa di testo.

By |Unity3D, Video Games Development|Commenti disabilitati su Get Component – Script from Another Object

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

Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

Inside Hierarchy create:

– Main Camera
– GUI Text X
– GUI Text Y
– GUI Text Z
– Cube (Game Object), attach ‘AccelerometerTest.js’

AccelerometerTest.js


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;
var scoreTextY : GUIText;
var scoreTextZ : GUIText;

	function Update () {
		var dir : Vector3 = Vector3.zero; // Shorthand for writing Vector3(0, 0, 0)
		
		dir.x = Input.acceleration.x;
		dir.y = Input.acceleration.y;
		dir.z = Input.acceleration.z;
		
		scoreTextX.text = "acceleration.x: "  + dir.x;
		scoreTextY.text = "acceleration.y: "  + dir.y;
		scoreTextZ.text = "acceleration.z: "  + dir.z;
		
	}

Hierarchy> Cube> Inspector> AccelerometerTest.js assign GUI Text to public var scoreText

Here the final result:

dir.x = Input.acceleration.x; from 1 to -1 -> example: 0.1234567 or -0.1234567
dir.y = Input.acceleration.y; from 1 to -1
dir.z = Input.acceleration.z; from 1 to -1

unity-001

unity-002

unity-003

To translate the Cube using Accelerometer data (basic):

AccelerometerTest.js


#pragma strict

function Update () 
{
    transform.Translate(Input.acceleration.x, 0, -Input.acceleration.z);
}

To translate the Cube using Accelerometer data (advanced):

AccelerometerTest.js


#pragma strict

	// Move object using accelerometer
	var speed = 10.0;

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

	function Update () {
		var dir : Vector3 = Vector3.zero; // Shorthand for writing Vector3(0, 0, 0)
		
		dir.x = Input.acceleration.x;
		
		scoreTextX.text = "acceleration.x: "  + dir.x;
		
		// clamp acceleration vector to unit sphere
		if (dir.sqrMagnitude > 1)
			dir.Normalize();
		
		// Make it move 10 meters per second instead of 10 meters per frame...
		dir *= Time.deltaTime;
			
		// Move object
		transform.Translate (dir * speed);
		
	}

unity-004

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

Unity 3D Game Engine – Long Touch – Counter Increase

Unity 3D Game Engine – Long Touch – Counter Increase

The counter will increase if you tap or long touch the device

1. Inside the Hierarchy create the structure:

– Main Camera
– GUI Text
– GameController (Empty Object), attach the ‘TouchController.js’

TouchController.js:


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreText : GUIText;
// touch counter, private because the users is not be able to change this value
private  var score : int;

function Start () {
        // The counter initial value is 0
        score = 0;
        scoreText.text = "No Touch:";
}

function Update() {
    if (Input.touchCount == 1) {
        // var score will increase if you tap or long touch the device
        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;
}


Hierarchy> GameController> TouchController.js assign over var Score Text the GUI Text Object

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Long Touch – Counter Increase