Table of Contents

2D Game Basics

Unity UI – Part 1 Unity Scripting – Part 1

Parameters

Parameters can be controlled in the editor as long as they are defined as public or serializable variables.

You can define both simple variables and lists (array)

public float speed;

public Sprite[] images;


[SerializeField]
private Text scoreText;
    
[SerializeField]
private GameObject[] enemyTypes;

Instantiating objects

Objects can be instantiated using the function

newobj = Instantiate(objTemplate) as ObjType;

//from pregab - prefab must be in Resources folder
newobj1 = Instantiate(Resources.Load("enemy"));

// Instantiate the projectile at the position and rotation of this transform
Rigidbody projectile;
Rigidbody clone;
clone = Instantiate(projectile, transform.position, transform.rotation);

enemyOrc = Instantiate(Orc) as Enemy;

Transforms

The transformations of an object can be accessed through the attribute `transform` (https://docs.unity3d.com/ScriptReference/Transform.html)

Vector3 objectPosition = GameObject.transform.position;

GameObject.transform.position = new Vector3(posX, posY, posZ);

transform.Translate(Vector3.up * Time.deltaTime, Space.World);

transform.Rotate(Vector3.up * Time.deltaTime, Space.World);

Random

To generate random values you can use the Random class

Random.Range(-10.0f, 10.0f)
Random.Range(0, 8);

Control of some objects or components

The display or hiding of an object in the scene can be done through the activation function.

myObject.SetActive(false); // hide
myObject.SetActive(true); // show

Similarly, the components of an object can be controlled

this.GetComponent<BoxCollider>().SetActive(false); // deactivate
this.GetComponent<SpriteRenderer>().sprite = image; //setting an image

myObject.GetComponent<Text>().text = '123' //setting a text

You can also access child or parent items

 childObject=parentObject.GetChild("child_name");

 //setarea unei componente a elementului copil
 parentObject.GetChild("child_name").GetComponent<SpriteRenderer>().sprite = image; 

Wait

If you want to introduce expectations when running a script / functions you can use custom keys. The corutines are used to start asynchronous functions, which can be extended on several frames, and in which you can put the wait (pause).

void Start()
{
    StartCoroutine(Example());
}

IEnumerator Example()
{
    print(Time.time);
    yield return new WaitForSeconds(5);
    print(Time.time);
}

Input Events

To be able to detect if an item has been pressed, the OnMouseDown function can be used

void OnMouseDown()
{        
      gameObject.SetActive(false);
}
    

Note! This function is active only if the user clicks on a UI element or a Collider

Tasks

Making a 2D memory game