Unreal Game Engine – C++ – Variables

Unreal Game Engine – C++ – Variables

You have to declare variables in your header file, see the sample below:

HelloWorldPrinter.h


#pragma once

#include "GameFramework/Actor.h"
#include "HelloWorldPrinter.generated.h"

/**
*
*/
UCLASS() // Questo rende Unreal Engine consapevoli della vostra nuova classe
class CODETESTPROJECT_API AHelloWorldPrinter : public AActor
{
	GENERATED_UCLASS_BODY()

	UPROPERTY() // Questo rende Unreal Engine consapevole della vostra nuova proprietà

	int32 MyNumberInt;   // declare an integer variable, 32-bit unsigned
	float MyNumberFloat; // declare a float number

	virtual void BeginPlay() override;


};// END UCLASS

To display variables values use your source file, see the sample below:


#include "CodeTestProject.h"
#include "HelloWorldPrinter.h" 

//Your class constructor
AHelloWorldPrinter::AHelloWorldPrinter(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
	MyNumberInt = 12;
	MyNumberFloat = 4.5;
}

// Dichiara la funzione - eseguita in BeginPlay() che è la funziona che unreal esegue all'inizio del game
void AHelloWorldPrinter::BeginPlay()
{
	Super::BeginPlay();

	if (GEngine) // Controllo se è valido l'oggetto globale GEngine
	{
		// Visualizza il testo a video
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, TEXT("My Variables: "));
		// Visualizza le varibili - key - time - color - string - variable
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, FString::FromInt(MyNumberInt));
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, FString::SanitizeFloat(MyNumberFloat));
	
	}
}

The result is:
4.5
12
My Variables:

NOTA BENE: sono messaggi di debug, vengono dati in sequenza, quello più in alto è l’ultimo.

By |Unity3D, Video Games Development|Commenti disabilitati su Unreal Game Engine – C++ – Variables

Unreal Game Engine – C++ Programming – Quick Start Guide

Unreal Game Engine – C++ Programming – Quick Start Guide

C++ (pronounced cee plus plus) is a general purpose programming language. It has imperative, object-oriented and generic programming features, while also providing the facilities for low level memory manipulation.

Unreal Engine does not have an internal code editor, you need to install Visual Studio od Visual studio Express.

1. Install the latest version of Internet Explorer
2. Install Visual Studio Express
3. Run Visual Studio

Increase the width of the Solution Configurations dropdown menu:
a. Right-click on the toolbar and select Customize (Personalizza) at the bottom of the menu that appears.
b. Click on the Commands tab (Comandi).
c. Select the Toolbar (Barra degli strumenti) radio button.
d. In the dropdown next to Toolbar, choose Standard.
e. In the Controls list at the bottom, select the Solution Configurations control (Configurazioni soluzione).
f. Click Modify Selection (Modifica selezione) on the right. Set the Width (larghezza) to “200”.
g. Click Close. Your toolbar should update immediately.

Add the Solution Platforms dropdown
Find the right-most button on the Standard toolbar, which opens a dropdown menu that will allow you to add and remove buttons from the toolbar.
Click the dropdown button, hover over Add or Remove Buttons, and then click on Solution Platforms (Piattaforme soluzione) to add the menu to the toolbar.

Turn off the Error List window
With Unreal Engine, the Error List can display false error information.

a. Close the Error List window if it is open.
b. From the Tools menu, open the Options dialog (Strumenti> Opzioni).
c. Select Projects and Solutions (Progetti e soluzioni) and uncheck Always show error list if build finishes with error (Mostra sempre Elenco errori se la compilazione finisce con errori).
d. Click OK

Create a New Project

1. Open Unreal Editor> New Project> Blank, name it ‘CodeTestProject’ uncheck ‘Include starter content’, click on ‘Create Project’ button

Add a New Class

1. MAIN TOP MENU> File> Add Code to Project> Actor
2. Name it ‘HelloWorldPrinter’> click ‘Create Class’ button, it will create in your project folder:
– HelloWorldPrinter.h (header)
– HelloWorldPrinter.cpp (c plus plus source)
3. In the next floating window click ‘Yes’ to edit now, Unreal will run Visual Studio Express

Visual Studio takes several minutes to analysing files, includes etc…, at the end you will se the message ‘Ready’ (Pronto), in the RIGHT COLUM> Solution Explorer (Esplora Soluzioni) you will see Games/CodeTestProject

Write the code:

HelloWorldPrinter.h


#pragma once

#include "GameFramework/Actor.h"
#include "HelloWorldPrinter.generated.h"

/**
 * 
 */
UCLASS() // Questo rende Unreal Engine consapevoli della vostra nuova classe
class CODETESTPROJECT_API AHelloWorldPrinter : public AActor
{
	GENERATED_UCLASS_BODY()

	UPROPERTY() // Questo rende Unreal Engine consapevoli della vostra nuova proprietà
	int32 MyNumber; // declare an integer variable

	virtual void BeginPlay() override;// Questo codice dichiara una funzione, ma lo fa eseguendo l'override di una funzione dalla classe padre.


};// END UCLASS

HelloWorldPrinter.cpp


#include "CodeTestProject.h"
#include "HelloWorldPrinter.h" 

//Your class constructor
AHelloWorldPrinter::AHelloWorldPrinter(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	MyNumber = 12;
}

// Dichiara la funzione - eseguita in BeginPlay() che è la funziona che unreal esegue all'inizio del game
void AHelloWorldPrinter::BeginPlay()
{
	Super::BeginPlay();

	if (GEngine) // Controllo se è valido l'oggetto globale GEngine
	{
		// Visualizza il testo a video
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, TEXT("Hello World!"));
		// Visualizza la variabile MyNumber
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, FString::FromInt(MyNumber));
	}
}

Save All

Compile the code

1. RIGHT COLUMN> Solution Explorer (Eslora Soluzioni)> RMB over yourproject (|++|CodeTestProject)> Build (Compila)

The process can take several minutes because it compile all the dependencies.

Using the New Class

1. Close Unreal Editor
2. Reopen the Unreal Editor and reload the Project
3. MAIN TOP MENU> Class Viewer> Filters> uncheck ‘Blueprint Bases Only’, search ‘HelloWorldPrinter’
4. DRAG and DROP Actor>HelloWorldPrinter (the Sphere icon), from the Class Viewer into 3D Viewport.
5. Play

Change the Class

1. Close Unreal Editor (if you do not close the Unreal Editor, Visual Studio can not overwrite the old file)
2. Inside Visual Studio open HelloWorldPrinter.cpp
3. Change … Yellow, TEXT(“Hello World!”) to …Yellow, TEXT(“Hello World Two!”)
4. RMB over yourproject (|++|CodeTestProject)> Build (Compila), the process takes only few seconds.
5. Reopen Unreal Editor
6. DRAG AND DROP Actor>HelloWorldPrinter (the Sphere icon), from the Class Viewer into 3D Viewport.
5. Play

Reference: https://docs.unrealengine.com/latest/INT/Programming/QuickStart/1/index.html

Editing an existing Project on the fly

0. Open Visual Studio> TOP TOOLBAR> Solutions Configurations (Configurazioni soluzioni)> DebugGame Editor
Questo significa che possiamo debuggare e aprire il progetto direttamente

1. Open Visual Studio Express> MAIn TOP MENU> File> Open Project (Apri Progetto)> select ‘CodeTestProject.sln’
2. RIGHT COLUMN> Solutions Explorer> click over Games/CodeTestProject/Source/HelloWorldPrinter.cpp
3. Change the script and save it
4. RIGHT COLUMN> Solutions Explorer> RMB over Games/CodeTestProject> Debug> Run New Instance (Avvia Nuova Istanza)

5. Unreal Enditor will be opened

Play to see changes

6. Switch to Visual Studio, change the script, save it.
7. Switch to Unreal Editor, MAIN TOP TOOLBAR> Compile> Recompile Game Code (Recompile and Reload C++ code on the fly)

Play to see changes
4. File> Save HelloWorldPrinter.cpp

For italian people: come funziona?

1. Visual Studio viene settato per permettere il debug direttamente all’interno di Unreal editor con ‘Configurazioni soluzioni> DebugGame Editor’
2. da visual Studio creo un ponte verso Unreal Editor con ‘Avvia Nuova Istanza’
3. da Unreal Editor posso ricompilare al volo direttamente dall TOOLBAR superiore con ‘Recompile Game Code’

By |Unity3D, Video Games Development|Commenti disabilitati su Unreal Game Engine – C++ Programming – Quick Start Guide

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