Tabla de Contenidos

Unity3D environtment (2D)

Basic tasks

Assets folder structure

Sprites

Scripting

Basic

Inherited functions

Properties

Interact with objects

// Calls the function ApplyDamage with a value of 5
gameObject.SendMessage ("ApplyDamage", 5.0);
...	
// Every script attached to the game object 
// that has an ApplyDamage function will be called.
function ApplyDamage (damage : float) {...

Input

Animations

Maths

Time

Interact with the scene

Persistence

Debug functions

Camera

The static object Camera.main contains the main camera for the scene.

Useful functions

How to do...

Move elements

:!:

// Directly
transform.position = new Vector3 (x, y, 0);
// Using transformations
transform.Translate (...)
// By physics
if(h * rigidbody2D.velocity.x < maxSpeed) rigidbody2D.AddForce(Vector2.right * h * moveForce);

Know which direction keys are we facing

float h = Input.GetAxis("Horizontal");
if(h > 0 && !facingRight) ...

Flip a character

Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;

Follow with effect

public float xMargin = 1f;		// Distance in the x axis the player can move before the camera follows.
public float yMargin = 1f;		// Distance in the y axis the player can move before the camera follows.
public float xSmooth = 8f;		// How smoothly the camera catches up with it's target movement in the x axis.
public float ySmooth = 8f;		// How smoothly the camera catches up with it's target movement in the y axis.
public Vector2 maxXAndY;		// The maximum x and y coordinates the camera can have.
public Vector2 minXAndY;		// The minimum x and y coordinates the camera can have.
// -----
float targetX = transform.position.x;
float targetY = transform.position.y;
// If the player has moved beyond the x margin...
if(CheckXMargin())
	// ... the target x coordinate should be a Lerp between the camera's current x position and the player's current x position.
	targetX = Mathf.Lerp(transform.position.x, player.position.x, xSmooth * Time.deltaTime);
// If the player has moved beyond the y margin...
if(CheckYMargin())
	// ... the target y coordinate should be a Lerp between the camera's current y position and the player's current y position.
	targetY = Mathf.Lerp(transform.position.y, player.position.y, ySmooth * Time.deltaTime);
// The target x and y coordinates should not be larger than the maximum or smaller than the minimum.
targetX = Mathf.Clamp(targetX, minXAndY.x, maxXAndY.x);
targetY = Mathf.Clamp(targetY, minXAndY.y, maxXAndY.y);
// Set the camera's position to the target position with the same z component.
transform.position = new Vector3(targetX, targetY, transform.position.z);

Scale interactively

healthBar.transform.localScale = new Vector3(healthScale.x * health * 0.01f, 1, 1);

Change an sprite color

healthBar.material.color = Color.Lerp(Color.green, Color.red, 1 - health * 0.01f);

Change an element to a foreground layer

go.sortingLayerName = "UI";

Disable an script

… Called PlayerControl.cs.

GetComponent<PlayerControl>.enabled = false;

Wait two secs and reload the level

StartCorroutine ("ReloadLevel");
//---
IEnumerator ReloadLevel () {
  yield return new WaitForSeconds (2);
  Application.LoadLevel(Application.levelLoaded);
}

Detect all enemies in a range

Collider2D[] enemies = Physics2D.OverlapCircleAll(transform.position, bombRadius, 1 << LayerMask.NameToLayer("Enemies"));
foreach(Collider2D en in enemies) {
Rigidbody2D rb = en.rigidbody2D;
if(rb != null && rb.tag == "Enemy") {
  rb.gameObject.GetComponent<Enemy>().HP = 0;

Make a gameObject invisible

Disabling its MeshRenderer component…

GetComponent(MeshRenderer).enabled = false;

For a finite amount of time…

StartCoroutine(Blink(2.0)); 
function Blink(waitTime : float) {
    var endTime=Time.time + waitTime;
    while(Time.time<waitTime){
        renderer.enabled = false;
        yield WaitForSeconds(0.2);
        renderer.enabled = true;
        yield WaitForSeconds(0.2);
    }
}

To make it blink always, immiately, and repeat every 0.4 seconds…

InvokeRepeating("Blink", 0, 0.4);
function Blink()
{
    renderer.enabled = false;
    yield WaitForSeconds(0.2);
    renderer.enabled = true;
}

Notes

Constants

#if UNITY_IOS && !UNITY_EDITOR
banner = new ADBannerView(ADBannerView.Type.Banner, ADBannerView.Layout.Top);
#endif

Physics

Scripting physics

Physics functions

Colliders

Materials

You can create a material to give a collider bouncingness or friction in Assets menu, Create and Physics 2D Material. It will have to be assigned to a collider.

How to...

... Detect a sprite collision by code

// Awake function
groundCheck = transform.Find("groundCheck");
// FixedUpdate
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground")); 

Detect it collides with

void OnCollisionEnter2D (Collision2D col)
{
	// If the colliding gameobject is an Enemy...
	if(col.gameObject.tag == "Enemy")

Apply force

Vector3 hurtVector = transform.position - enemy.position + Vector3.up * 5f;
rigidbody2D.AddForce(hurtVector * hurtForce);

Disable colliders

Collider2D[] colliders = GetComponents<Collider2D>();
foreach (var c in colliders) c.isTrigger = true;

Move an element

float inputX = Input.GetAxis("Horizontal");
float inputY = Input.GetAxis("Vertical");
movement = new Vector2(speed.x * inputX, speed.y * inputY);

Other stuff...

Working with mobile phones

There's an app to test mobile input named Unity Remote.

GUI elements

GUI.Label(new Rect(), message);
if (GUI.Button()) {

To make a property which won't be shown in the editor:

[HideInInspector]
public float mAngle = 0f;

To create a option menu you will add a class of the next style:

using UnityEngine;
using UnityEditor;
using System.Collections;
 
public class FunWindow : EditorWindow
{
	[MenuItem("Tools/Fun Window")]
	public static void ShowWindow()
	{	
		EditorWindow.GetWindow<FunWindow>("Fun Window");
	}
 
	void OnGUI()
	{
		if(GUILayout.Button("Clear PlayerPrefs"))
		{
			PreferencesManager.DeleteAll();
		}
 
		if(GUILayout.Button("Clear Store"))
		{
			Unibiller.clearTransactions();
		}
	}
}

Coroutines

Wait for seconds requires a couple things in order to work properly and chances are if it's not working you're probably just missing on of the requirements. Here's an example:

IEnumerator MyMethod() {
 Debug.Log("Before Waiting 2 seconds");
 yield return new WaitForSeconds(2);
 Debug.Log("After Waiting 2 Seconds");
}
Simple right? The only trick here is to make sure the return type of the method using the `WaitForSeconds` call is `IEnumerator`. Okay, so now we're half done but the next thing is to call this `MyMethod` and that looks like:

StartCoroutine(MyMethod());
And there's the 2nd trick. You need to call the method as a coroutine otherwise you're not going to have it work.

Now that you get how it works, jump back to the yield statement. Anything you want to happen after the wait goes after the yield statement and everything you want to happen before, goes before the yield statement. Hope this helps!

Social API