Unity – Object Oriented Programming – OOP

Unity – Object Oriented Programming – OOP

OOP is the best way to organize your data.

NOTICE:
‘public class SingleCharacterScript’ -> deve avere lo stesso nome dello script senza l’estensione ‘SingleCharacterScript.js’

La classe è un contenitore per variabili e funzioni, ad esempio ‘public class Stuff’ contiene variabili e funzioni, è un buon modo per raggruppare cose che funzionano insieme.

Programmare in OOP significa dividere uno script in più script, ogniuno dei quali si occupa di uno specifico compito.

Qui sotto abbiamo:
– una porzione di codice ‘public class Stuff’ che contiene solo l’inventario dei proiettili, granate, missili.
– una per il movimento ‘function Movement ()’
– una per lo sparo ‘function Shoot ()’

Single Script

SingleCharacterScript.js

#pragma strict

public class SingleCharacterScript extends MonoBehaviour
{
    public class Stuff
    {
        public var bullets : int;
        public var grenades : int;
        public var rockets : int;
        
        public function Stuff(bul : int, gre : int, roc : int)
        {
            bullets = bul;
            grenades = gre;
            rockets = roc;
        }
    }
    
    
    public var myStuff : Stuff = new Stuff(10, 7, 25);
    public var speed : float;
    public var turnSpeed : float;
    public var bulletPrefab : Rigidbody;
    public var firePosition : Transform;
    public var bulletSpeed : float;
    
    
    function Update ()
    {
        Movement();
        Shoot();
    }
    
    
    function Movement ()
    {
        var forwardMovement : float = Input.GetAxis("Vertical") * speed * Time.deltaTime;
        var turnMovement : float = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
        
        transform.Translate(Vector3.forward * forwardMovement);
        transform.Rotate(Vector3.up * turnMovement);
    }
    
    
    function Shoot ()
    {
        if(Input.GetButtonDown("Fire1") && myStuff.bullets > 0)
        {
            var bulletInstance : Rigidbody = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation);
            bulletInstance.AddForce(firePosition.forward * bulletSpeed);
            myStuff.bullets--;
        }
    }
}

Split in Multiple Scripts

With OOP we can split the ‘SingleCharacterScript.js’ into Multiple Script:
– Inventory.js -> public class Inventory + subclass Stuff
– MovementControls.js -> variables and functions
– Shooting.js -> variables and functions

Look at Inventory.js

– main class ‘public class Inventory’
– sub class ‘public class Stuff’ nested inside ‘public class Inventory’
– variables ‘public var bullets : int; etc…’
– constructor ‘public function Stuff ()’ it needs the same name of the class ‘Stuff’, to assign default values to variables of a class

You can construct an object in this way:

public function Stuff () // assegno valori senza variare la tipologia di variabile
        {
            bullets = 1;
            grenades = 1;
            rockets = 1;
        }

Or in this way:

public function Stuff(bul : int, gre : int, roc : int) // specifico di che tipo di variabile si tratta
        {
            bullets = bul;
            grenades = gre;
            rockets = roc;
        }

Creare un’istanza delle variabili, praticamente un nuovo oggetto che si basa su uno già esistente.
Notare che ‘Stuff= new Stuff’ dove ‘Stuff’ è lo stesso nome della classe

public var myStuff : Stuff= new Stuff(50, 5, 5);

In caso di costruttori multipli:

public var myStuff : Stuff= new Stuff(50, 5, 5);
USERA’
public function Stuff(bul : int, gre : int, roc : int)
PERCHE’ I PARAMETRI CORRISPONDONO (notare int – int – float)

INVECE

public var myOtherStuff : Stuff= new Stuff(50, 1.5f);
USERA’
public function Stuff(bul : int, fu : float)
PERCHE’ I PARAMETRI CORRISPONDONO (notare int – float)

Attach the Multiple Script at the SAME OBJECT

Inventory.js

#pragma strict

public class Inventory extends MonoBehaviour
{
    public class Stuff // this is a subclass nested inside class Inventory
    {
        public var bullets : int;
        public var grenades : int;
        public var rockets : int;
        public var fuel : float;
        
        public function Stuff(bul : int, gre : int, roc : int)
        {
            bullets = bul;
            grenades = gre;
            rockets = roc;
        }
        
        public function Stuff(bul : int, fu : float)
        {
            bullets = bul;
            fuel = fu;
        }
        
        // Constructor
        public function Stuff ()
        {
            bullets = 1;
            grenades = 1;
            rockets = 1;
        }
    }
    
    
    // Creating an Instance (an Object) of the Stuff class
    public var myStuff : Stuff= new Stuff(50, 5, 5);
    
    public var myOtherStuff : Stuff= new Stuff(50, 1.5f);
    
    function Start ()
    {
        Debug.Log(myStuff.bullets); 
    }
}

MovementControls.js

#pragma strict

public var speed : float;
public var turnSpeed : float;


function Update ()
{
    Movement();
}


function Movement ()
{
    var forwardMovement : float = Input.GetAxis("Vertical") * speed * Time.deltaTime;
    var turnMovement : float = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
    
    transform.Translate(Vector3.forward * forwardMovement);
    transform.Rotate(Vector3.up * turnMovement);
}

Shooting.js

#pragma strict

public var bulletPrefab : Rigidbody;
public var firePosition : Transform;
public var bulletSpeed : float;


private var inventory : Inventory;


function Awake ()
{
    inventory = GetComponent(Inventory);
}


function Update ()
{
    Shoot();
}


function Shoot ()
{
    if(Input.GetButtonDown("Fire1") && inventory.myStuff.bullets > 0)
    {
        var bulletInstance : Rigidbody = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation);
        bulletInstance.AddForce(firePosition.forward * bulletSpeed);
        inventory.myStuff.bullets--;
    }
}
By |Unity3D|Commenti disabilitati su Unity – Object Oriented Programming – OOP

Unity – Functions

Unity – Functions

A function is a type of procedure or routine, a block of code inside curly braces {} that will be executed when “someone” calls it. Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. With functions you can write less code and do more!

The code:


#pragma strict

var myInt : int = 5;


function Start ()
{
    myInt = MultiplyByTwo(myInt);
    Debug.Log (myInt);
}


function MultiplyByTwo (number : int) : int
{
    var ret : int;
    ret = number * 2;
    return ret;
}

It means:

function Start ()
Unity function. It is called when the unity object enters in the scene.
Start() function does not return anything.


var myInt : int = 5;

var – dichiaro che è una variabile – nome della variabile – myInt : tipo (intero) = 5 (valore inziale)


function MultiplyByTwo (number : int) : int … return ret;

function – dichiaro che è una funzione – nome della funzione ‘MultiplyByTwo’ – (creo una variabile temporanea ‘number’ : la variabile temporanea è un intero – int -) : il tipo della funzione è intero – int -, cioè il suo risultato sarà un numero intero … la funziona ritorna il valore della variabile ‘ret’;

NOTA: la variabile ‘number’ è privata della funzione ‘ MultiplyByTwo’ che la utilizza al solo fine di eseguire i suoi compiti, non è una variabile che posso richiamare al di fuori della funzione.


myInt = MultiplyByTwo(myInt);

Il nuovo valore della variabile ‘myInt’ lo ottengo mettendo in azione la funzione ‘ MultiplyByTwo’, in particolare invio alla funzione il valore di inizializzazione di ‘myInt’, cioè 5, la funzione assegna questo valore alla sua variabile temporanea privata ‘number’, esegue i calcoli e ritorna come risultato il valore di ‘ret’. Tornando all’inizio quindi ‘myInt’=’ret’ -> 10

By |Unity3D|Commenti disabilitati su Unity – Functions

Unity – Scene View Navigation

Unity – Scene View Navigation

SCENE VIEW

MAIN TOP MENU> Window> Scene

Shortcuts View:

Q + LMB -> PAN VIEW
Q + RMB -> LOOK AROUND FIRST PERSON STYLE
ALT + LMB -> LOOK AT
ALT + RMB -> ZOOM

Shortcuts Objects:

F -> FOCUS CURRENT OBJECT
W + LMB -> MOVE OBJECT
E + LMB -> ROTATE OBJECT
R + LMB -> SCALE OBJECT

Menu:

Textured
Wireframe
Textured Wireframe
Render Path
LightMap Resolution

RGB
Alpha
Overdraw
Mipmaps

2D
3D

Light ON/OFF

Audio ON/OFF

Effects Skybox / Fog / Flares / Animated Material

Gizmos / Grid SETUP

SEARCH Object

WIEW GIZMO (to switch in ‘perspective view’ mode click over the white box)

GAME VIEW

2. MAIN TOP MENU> Window> Game

Menu:

Free Aspect
5:4
4:3
3:2
16:10
16:9

Standalone (1024×768) setup this:
Edit> Project Settings> Player> Inspector> Settings for PC, MAc LinuX Standalone
Uncheck ‘Default is Full Screen’ and setup ‘Default Screen Width’ and ‘Default Screen Height’

Mazimize on Play

Stats
Verts, VRAM etc…

Gizmos / Grid SETUP

By |Unity3D|Commenti disabilitati su Unity – Scene View Navigation

Unity – Object follow cursor pointer

Unity – Object follow cursor pointer

DRAG AND DROP this script over an Object inside Hierarchy

#pragma strict

function Start () 
{ 
 Screen.showCursor = false; 
} 

// -------------------------------
// FOLLOW MOUSE POSITION START
// -------------------------------
public var depth = 10.0; 

function FollowMousePosition()
{ 
 var mousePos = Input.mousePosition; 
     var wantedPos = Camera.main.ScreenToWorldPoint (Vector3 (mousePos.x, mousePos.y, depth)); 
     transform.position = wantedPos; 
}
// -------------------------------
// FOLLOW MOUSE POSITION END
// -------------------------------

function Update () 
{ 
 FollowMousePosition();  
}

NOTICE: mousePos.x – mousePos.y

By |Unity3D|Commenti disabilitati su Unity – Object follow cursor pointer

Unity – LookAt 2D – Mouse Position

Unity – LookAt 2D – Mouse Position

Instead of ‘Transform.LookAt’ Unity function you can use Mathematic.

1. DRAG AND DROP this script over the object you want to look at target

var mouse_pos : Vector3;
var target : Transform; //Assign to the object you want to rotate
var object_pos : Vector3;
var angle : float;
 
function Update ()
{
    mouse_pos = Input.mousePosition;
    mouse_pos.z = 5.23; //The distance between the camera and object
    object_pos = Camera.main.WorldToScreenPoint(target.position);
    mouse_pos.x = mouse_pos.x - object_pos.x;
    mouse_pos.y = mouse_pos.y - object_pos.y;
    angle = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(Vector3(0, 0, angle));
}

2. Inspector> select the target for the variable ‘Target’
3. Play!

By |Unity3D|Commenti disabilitati su Unity – LookAt 2D – Mouse Position