Unity3D – Object Pooling – Bullets – CSharp

Unity3D – Object Pooling – Bullets – CSharp

Object Pooling è una tecnica per ridurre i calcoli della CPU.

Questo sistema di programmazione consiste nel creare un gruppo di oggetti, storarli inattivi all’interno di una lista, per poi attivarli e posizionarli direttamente nell’area di gioco.

La generazione di tutti gli oggetti comporta un consumo di RAM iniziale elevato, che comunque è molto meno costoso in termini di prestazioni del dover ogni volta istanziare e distruggere i singoli eggetti.

Applicare questa tecnica ha senso se utilizziamo a video nello stesso tempo almeno diverse centinaia di oggetti o stiamo sviluppando su piattaforma mobile dove la potenza di calcolo della CPU non è elevata.

Creiamo una scena con:

(parent) Spaceship
– (child) Bullet

All’oggetto ‘Bullet’ applichiamo:

BulletScript.cs


using UnityEngine;
using System.Collections;

public class BulletScript : MonoBehaviour {

	public float speed = 5;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		// simple move the object
		transform.Translate (0, speed * Time.deltaTime, 0);
	
	}

}// END MonoBehaviour

Questo script semplicemente muove l’oggetto

BulletDestroyScript.cs


using UnityEngine;
using System.Collections;

public class BulletDestroyScript : MonoBehaviour {

	// This function is called when the object becomes enabled and active.
	// It is a part of MonoBehaviour.OnEnable()
	void OnEnable()
	{
		Invoke ("Destroy", 2f); // call the function after 2 second
	}

	void Destroy()
	{
		gameObject.SetActive (false); // deactivate the object
	}

	// This function is called when the behaviour becomes disabled () or inactive.
	// It is a part of MonoBehaviour.OnDisable()
	void OnDisable()
	{
		CancelInvoke();
	}
	
}// END MonoBehaviour

Questo script disattiva l’oggetto dopo 2 secondi per ottimizzare il rendering

All’oggetto ‘Spaceship’ applichiamo:

BulletFireScript.cs


using UnityEngine;
using System.Collections;
using System.Collections.Generic; // to add Lists

public class BulletFireScript : MonoBehaviour {

	public float fireTime = .1f; // attiva un oggetto bullet ogni xxx secondi
	public GameObject bullet; // Assign in Inspector

	public int pooledAmount = 20; // numero di oggetto instanziati, se insufficienti aumentarli 
	public List<GameObject> bullets;

	// Use this for initialization
	void Start () {
		// crea una lista di oggetti inattivi
		bullets = new List<GameObject> (); 

		for (int i = 0; i < pooledAmount; i++) 
		{
			GameObject obj = (GameObject)Instantiate(bullet);
			obj.SetActive (false); // inattivi, verranno attivati dalla funzione Fire()
			bullets.Add (obj); // aggiungi l'oggetto alla lista
			Debug.Log(bullets.Count);
		}
		InvokeRepeating ("Fire", fireTime, fireTime); // richiama la funzione Fire()
	}// END Start

	void Fire() {
		// posiziona e attiva tutti gli aoggetti della lista bullets
		for (int i=0; i < bullets.Count; i++)// scorre tutti gli oggetti della scena
		{
			if (!bullets[i].activeInHierarchy)// se un oggetto nella scena non è attivo
			{
				bullets[i].transform.position = transform.position;// posiziona
				bullets[i].transform.rotation = transform.rotation;// rotazione
				bullets[i].SetActive(true);// attiva
				break;			
			}// END if
		}
	}// END Fire

}// END MonoBehaviour
	

Assegniamo in Inspector l’oggetto ‘Bullet’ alla variabile ‘bullet’

Questo script:
1. Crea una lista
2. Start () -> Instanzia 20 oggetti, li disattiva e li inserisce nella lista
3. Fire() -> posiziona gli oggetti e li attiva

Avviate il gioco, osservate Hierarchy e Inspector per BulletFireScript.cs per comprenderne il funzionamento

Si può notare dal codice di tutti gli script che – Destroy (gameObject) – NON è mai stata utilizzata, perchè i 20 oggetti bullet vengono continuamente riciclati attivandoli e disattivandoli di continuo.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Object Pooling – Bullets – CSharp

Unity3D – What is Object Pooling

Unity3D – Object Pooling

What is a pool?
In computer science, a pool (piscina) is a set of initialised resources that are kept ready to use, rather than allocated and destroyed on demand.
A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished with an object (or resource), it returns it to the pool rather than destroying it.

What is object pooling?
In games you need to manage a lot gameobjects at one time (bullets, enemies etc…), and istantiate and destroy every object can slow down your game performance.
To improve performance and save CPU time the best way is create a pool of gameobjects and request gameobjects from the pool.

For example you can have an gameObject off screen named “enemies” which holds all the enemies, and a master script to manage it:

enemies (Empty Game Object) -> master script ‘Enemy.js’
|
|—-enemy
|
|—-enemy
|
|—-enemy

Another example is reuse bullets:

Slower performance:
1. Awake(), do nothing
2. Update()
a- Instantiate bullet in its start position
b- Move along the way
c- Move bullet in its final position
d- Destroy bullet

Object Pooling. best performance:
1. Awake(), create a pool off screen
2. Update ()
a- Get gameobject bullet from the pool
b- SetActive -> true, Move bullet in its start position
c- Move along the way
d- Move bullet in its final position
e- SetActive -> false
f- Reuse from point b- and so on…

In terms of performance for real scenarios, if you use only 10-50 gameobjects at one time the benefits of object pooling are irrelevant.

In Unity3D you will need object pooling when you have thousands of gameObjects at one time or if you develop for slower mobile devices.

References:

http://answers.unity3d.com/questions/321762/how-to-assign-variable-to-a-prefabs-child.html

http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – What is Object Pooling

Unity3D – Scrolling Typewriter effect – JavaScript

Unity3D – Scrolling Typewriter effect – JavaScript

Create a scene with:

– TextMesh
– Empty Object, assign TypeWriter.js

#pragma strict

var displayText : TextMesh;

var textShownOnScreen: String ;
var fullText : String = "The text you want shown on screen with typewriter effect.";
var wordsPerSecond : float = 2; // speed of typewriter, words per second
var timeElapsed : float = 0;   
 
function Update()
{
    timeElapsed += Time.deltaTime;
    textShownOnScreen = GetWords(fullText, timeElapsed * wordsPerSecond);
    displayText.text = textShownOnScreen;
}
 
function GetWords(text : String, wordCount : int): String
{
    var words : int = wordCount;
 
    // loop through each character in text
    for (var i : int = 0; i < text.Length; i++)
    { 
        if (text[i] == ' ')
        {
            words--;
        }
 
        if (words <= 0)
        {
            return text.Substring(0, i);
        }
    }
 
    return text;
}

Inspector, assign a 3DText to var displayText.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Scrolling Typewriter effect – JavaScript

Unity3D – Explosion Force – JavaScript

Unity3D – Explosion Force – JavaScript

Create a scene with:

– Plane (Collider)

– Cube1 (Collider + Rigid Body)
– Cube2 (Collider + Rigid Body)
– Cube3 (Collider + Rigid Body)

– Sphere (SphereExplosion.js)

SphereExplosion.js:

#pragma strict

	var radius = 50.0; // radius of explosion
	var power = 500.0; // power of explosion
	var bombObject : GameObject; // Assign in Inspector the Bomb GameObject
	
	
function Start () {
}
	
function OnMouseDown ()
{
        // When you click over the object
        
                // Force START -----------------------------------------------------------
                // Applies an explosion force to all nearby rigidbodies
		var explosionPos : Vector3 = bombObject.transform.position;
		// Returns an array with all colliders touching or inside the sphere.
		var colliders : Collider[] = Physics.OverlapSphere (explosionPos, radius);
		
		for (var hit : Collider in colliders) {
			if (hit && hit.rigidbody)
				hit.rigidbody.AddExplosionForce(power, explosionPos, radius, 3.0);
		}
		 // Force END -------------------------------------------------------------
		
}

function Update () {
}

Inspector> Assign the Sphere Mesh to var bombObject, setup var radius and var power

Play and click over the Sphere… boom!!!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Explosion Force – JavaScript

Unity3D – Drivable Vehicle – JavaScript – Super Easy

Unity3D – Drivable Vehicle – JavaScript – Super Easy

Create a scene with:

– (parent) CarBody (Box Object) -> Add Rigid Body -> Mass 200
– (child) CarWheelFR (Empty Object) -> Add WheelCollider
– (child) CarWheelFL (Empty Object) -> Add WheelCollider
– (child) CarWheelRR (Empty Object) -> Add WheelCollider
– (child) CarWheelRL (Empty Object) -> Add WheelCollider

CarBody, add the script:


#pragma strict

// Assign in Inspector
var CarWheelFR : WheelCollider; // Front Right
var CarWheelFL : WheelCollider; // Front Left
var CarWheelRR : WheelCollider; // Rear Right
var CarWheelRL : WheelCollider; // Rear Left

var Speed: float = 10; 
var Breaking: float = 20; 
var Turning: float = 20; 

function Start () {
}// END Start

function Update () {
	// This code makes the car go foward and backward - notare che è a trazione posteriore
	// simulate the whell rotation - spinta
	CarWheelRR.motorTorque = Input.GetAxis("Vertical")*Speed; // arrow up / down
	CarWheelRL.motorTorque = Input.GetAxis("Vertical")*Speed;
	
	// reset the variable, if you miss this code 'CarWheelRR.brakeTorque = Breaking;' for ever after get Space key button
	CarWheelRR.brakeTorque = 0;
	CarWheelRL.brakeTorque = 0;
	
	// This code makes the car turn
	// simulate the steer - sterzata
	CarWheelFR.steerAngle = Input.GetAxis("Horizontal")*Turning; // arrow left / right
	CarWheelFL.steerAngle = Input.GetAxis("Horizontal")*Turning;
	
	if (Input.GetKey(KeyCode.Space))
	{
		// simulate the brake, frenata
		CarWheelRR.brakeTorque = Breaking;
		CarWheelRL.brakeTorque = Breaking;
	}
	
}// END Update

Assign in Inspector var CarWheelFR CarWheelFL CarWheelRR CarWheelRL

Play

For italian people: come funziona?
1. Monto l’auto con il corpo e le ruote, imparentando le ruote a CarBody, come nella realtà
2. Con l’input da tastiera sfrutto le proprietà del Collider WheelCollider: .motorTorque .steerAngle .brakeTorque

Vedi API a: http://docs.unity3d.com/ScriptReference/WheelCollider.html

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Drivable Vehicle – JavaScript – Super Easy