Panel de proyecto -> Create -> Script de C# -> Asocio el script a un nuevo Empty llamado "EscenaManagement".
Editor
Si estamos usando windows, lo normal es usar el visual studio. Pero si usamos linux, podemos usar el mono develop. Para vincular el monodevelop a unity3d usaremos: Edit -> Preferences -> External Tools -> monodevelop
Hola Mundo
public class HolaMundo : MonoBehaviour {
void Start () {
Debug.Log ("Hola Mundo");
}
void Update () {
Debug.Log ("Adios Mundo");
}
}
Variables
Declaración
public class Variables : MonoBehaviour {
string textoInicio = "Hola Mundo!";
void Start () {
Debug.Log (textoInicio);
}
void Update () {
}
}
Tipos de variables
public class TiposVariables : MonoBehaviour {
public int numeroEntero = 1; // 1 2 3 4 5 6 7 8 ...
public float numeroDecimal = 1.2f; //1.1f 1.2f 1.33f ...
public string texto = "El texto"; // "Van siempre entre comillas"
public bool variableBooleana;
// variables típicas de Unity
public GameObject cubos;
public Transform miTransform;
public MeshFilter meshFilter;
public BoxCollider boxCollider;
public MeshRenderer meshRender;
void Start () {
}
void Update () {
}
}
Si arrastro este script a un GameObject, podré modificar las variables seleccionando el GameObject desde el panel Inspector.
Concatenaciones
public class Concatenaciones : MonoBehaviour {
string v1 = "Buenos días ";
string v2 = "Pablo";
void Start () {
Debug.Log (v1 + v2);
}
}
Operaciones aritméticas
public class OperacionesAritmeticas : MonoBehaviour {
int a = 6;
int b = 8;
void Start () {
Debug.Log (a + b + "suma");
Debug.Log (a - b + "resta");
Debug.Log (a / b + "division");
Debug.Log (a * b + "multiplicacion");
Debug.Log (a % b + "resto");
Debug.Log (++a + "incremento");
Debug.Log (--a + "decremento");
}
}
Condicionales
public class Condicionales : MonoBehaviour {
public int velocidadCoche = 0;
void Start () {
}
void Update () {
if(velocidadCoche > 40){
Debug.Log ("Vas muy rápido");
}else if(velocidadCoche < 38){
Debug.Log ("Vas muy lento");
}else{
Debug.Log (velocidadCoche);
}
velocidadCoche++;
}
/*
a > b
a < b
a >= b
a <= b
a == b
a != b
a > b && a > 3
a > b || a > 3
*/
}
Arrays
No es posible cambiar dinámicamente su tamaño.
public class Arrays : MonoBehaviour {
string [] letras = new string[]{"a", "b", "c", "d", "e"};
void Start () {
Debug.Log (letras [2]);
}
}
Obtener un nuevo array con una posición eliminada
public static class Tools{
public static T[] GetNewArrayRemovingAt<T>(this T[] source, int index){
T[] dest = new T[source.Length - 1];
if (index > 0)
Array.Copy(source, 0, dest, 0, index);
if (index < source.Length - 1)
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
}
miArray = miArray.GetNewArrayRemovingAt(indice);
Listas
Es posible cambiar dinámicamente su tamaño.
Ejemplo de creación de una lista de enterosList<int> numeros = new List<int>(new int[]{ 1,2,3});
Eliminamos el segundo elemento de la listanumeros.RemoveAt(2);
Bucle for
public class Bucles : MonoBehaviour {
public int [] numeros = new int[6]{0, 1, 2, 3, 4, 5};
void Start () {
for (int i = 0; i < numeros.Length; i++) {
Debug.Log (numeros[i]);
}
}
}
Bucle foreach
public class BucleForeach : MonoBehaviour {
string[] animales = { "perro", "gato", "elefante" };
void Start () {
foreach(string animal in animales){
Debug.Log(animal);
}
}
}
Bucle doWhile
public class BucleDoWhile : MonoBehaviour {
string[] animales = { "perro", "gato", "elefante" };
void Start () {
int i = 0;
do{
Debug.Log(animales[i]);
i++;
}while(i < animales.Length );
}
}
Switch Case
public class SwitchCase : MonoBehaviour {
int caso = 1;
void Start () {
switch(caso){
case 0:
Debug.Log("aaaaaaaaa");
break;
case 1:
Debug.Log ("bbbbbbbbb");
break;
default:
break;
}
}
}
Funciones
public class Funciones : MonoBehaviour {
void Start () {
saludar ();
}
void saludar(){
Debug.Log ("hola");
}
}
Función con parámetros
public class FuncionConParametros : MonoBehaviour {
void Start () {
saludar ("Juan");
}
void saludar (string nombre) {
Debug.Log ("hola " + nombre);
}
}
Función con parámetros y return
public class FuncionConReturn : MonoBehaviour {
void Start () {
string saludo = saludar ("Juan");
Debug.Log (saludo);
}
string saludar (string nombre) {
string txt = "hola " + nombre;
return txt;
}
}
Programación orientada a objetos
public class Coche{
public string marca;
public int cantidadRuedas;
public void encenderMotor (){
Debug.Log ("El motor está encendido");
}
public void apagarMotor(){
Debug.Log ("El motor está apagado");
}
}
public class Carretera : MonoBehaviour {
Coche miCoche;
void Start(){
crearCoche ();
}
void crearCoche(){
miCoche = new Coche ();
miCoche.marca = "Ford";
miCoche.cantidadRuedas = 4;
miCoche.encenderMotor ();
Debug.Log ("La marca de mi coche es " + miCoche.marca);
Debug.Log ("Mi coche tiene " + miCoche.cantidadRuedas + " ruedas");
apagarCoches ();
}
void apagarCoches(){
miCoche.apagarMotor ();
}
}
Las clases que heredan de MonoBehaviour nos permiten sobrecargar el método update.