Monday, August 28, 2017

Usando Player Prefs fuera del modo de juego

Muchas veces usamos la clase Player Prefs para guardar datos. Pero que pasa cuando queremos borrar los datos guardados?. Yo solia colocar esta linea de codigo:

PlayerPrefs.DeleteAll();

Compilar, ejecutar, borrar linea de codigo, compilar y ejecutar otra vez.

Pero ahora las cosas han cambiado. Vamos a colocar un item en el menu que nos permita ejecutar esa linea de codigo en cualquier momento.

Primero creamos una clase con el nombre  DeletePlayerPrefsData  y agregamos el codigo:

using UnityEngine;
using UnityEditor;

public class DeletePlayerPrefsData {
[MenuItem("Assets/Delete Player Prefs")]
public static void DeletePlayerPrefs() {
PlayerPrefs.DeleteAll();
}
}

Aqui colocamos en que parte del menu se encuentra el script
[MenuItem("Assets/Delete Player Prefs")]

Y por ultimo declaramos una funcion estatica justo abajo de  [MenuItem] que sera la funcion a ejecutar cuando demos click a  Delete Player Prefs  en el menu.

Using Player Prefs on Unity outside play mode

Often I like to use Player Prefs to store user data, because is really easy to use. But what happens when we want to delete it?. I used to put this line of code:

PlayerPrefs.DeleteAll();

Complite, execute, erase line of code, compile and execute again.

Now I know better!, so we are going to setup a Menu Item to execute this at any time.

Lets create a new C# script, name it  DeletePlayerPrefsData  and add the following code:

using UnityEngine;
using UnityEditor;

public class DeletePlayerPrefsData {
[MenuItem("Assets/Delete Player Prefs")]
public static void DeletePlayerPrefs() {
PlayerPrefs.DeleteAll();
}
}

Here we put the location of the script function on the menu.
[MenuItem("Assets/Delete Player Prefs")]

Lastly we declare a static function just below  [MenuItem]  which would be the function that will execute when  Delete Player Prefs  is clicked.



Wednesday, August 23, 2017

Como definir regiones de codigo para una o varias plataformas

English

Digamos que queremos ejecutar una parte del codigo para cierta plataforma, muchas veces este problema ocurre cuando tenemos un proyecto multiplataforma que poseen caracteristicas distintas entre ellas.

Comunmente queremos hacer esto con los controles de usuario entre PC y Móviles.

void Update () {
    if (Input.GetKey(KeyCode.D)) { //Mover a la derecha
        rigidbody2D.velocity = new Vector2(speed0.0f);
    }
    else if (Input.GetKey(KeyCode.A)) { //Mover a la izquierda
        rigidbody2D.velocity = new Vector2(-speed0.0f);
    }
    else { //No hay movimiento
        rigidbody2D.velocity = new Vector2(0.0f0.0f);
    }
}

En moviles esto no funciona.

Podemos agregar el codigo de la entrada por pantalla tactil abajo del codigo que tenemos pero esto hace que todo ese sea ejecutado sin importar si la plataforma lo soporta o no. Aqui es cuando usamos las directivas especificas de plataforma.

    void Update () {
#if UNITY_STANDALONE || UNITY_WEBGL || UNITY_EDITOR //PC
        if (Input.GetKey(KeyCode.D)) { //Mover a la derecha
            rigidbody2D.velocity = new Vector2(speed0.0f);
        }
        else if (Input.GetKey(KeyCode.A)) { //Mover a la izquierda
            rigidbody2D.velocity = new Vector2(-speed0.0f);
        }
        else { //No hay movimiento
            rigidbody2D.velocity = new Vector2(0.0f0.0f);
        }
#elif UNITY_ANDROID || UNITY_IOS //Movil
        if (Input.GetTouch(0).position.x > Screen.width / 2.0f) { //Mover a la derecha
            rigidbody2D.velocity = new Vector2(speed0.0f);
        }
        else if (Input.GetTouch(0).position.x < Screen.width / 2.0f) { //Mover a la izquierda
            rigidbody2D.velocity = new Vector2(-speed0.0f);
        }
        else { //No hay movimiento
            rigidbody2D.velocity = new Vector2(0.0f0.0f);
        }
#endif
    }

Aqui definimos ciertas regiones de codigo que solo seran compiladas si la plataforma actualmente seleccionada es la misma que en  #if / #elif  definidos.


Para mas informacion acerca de cual propiedad usar para cada plataforma puedes chequear la tabla con todas las posibles propiedades.

Define code regions for specific platforms

Español

Let's say we want to execute especific code for a certain platform, usually this problem arises when we are targeting multiple platforms and some features/characteristics are different.

Often we want to do this with the input between PC and Mobile, so if we have this on PC.

void Update () {
    if (Input.GetKey(KeyCode.D)) { //Move right
        rigidbody2D.velocity = new Vector2(speed0.0f);
    }
    else if (Input.GetKey(KeyCode.A)) { //Move left
        rigidbody2D.velocity = new Vector2(-speed0.0f);
    }
    else { //Does not move
        rigidbody2D.velocity = new Vector2(0.0f0.0f);
    }
}

On mobile this won't work.

We could add the mobile input code next to it but everything will be executed, so here's where we use Platform #define directives.

    void Update () {
#if UNITY_STANDALONE || UNITY_WEBGL || UNITY_EDITOR //PC Input
        if (Input.GetKey(KeyCode.D)) { //Move right
            rigidbody2D.velocity = new Vector2(speed0.0f);
        }
        else if (Input.GetKey(KeyCode.A)) { //Move left
            rigidbody2D.velocity = new Vector2(-speed0.0f);
        }
        else { //Does not move
            rigidbody2D.velocity = new Vector2(0.0f0.0f);
        }
#elif UNITY_ANDROID || UNITY_IOS //Mobile Input
        if (Input.GetTouch(0).position.x > Screen.width / 2.0f) { //Move right
            rigidbody2D.velocity = new Vector2(speed0.0f);
        }
        else if (Input.GetTouch(0).position.x < Screen.width / 2.0f) { //Move left
            rigidbody2D.velocity = new Vector2(-speed0.0f);
        }
        else { //Does not move
            rigidbody2D.velocity = new Vector2(0.0f0.0f);
        }
#endif
    }

In this we define certain code regions that will only be compiled if the current selected platform matches the property inside the  #if / #elif  statements.


For more info on which property to use check the table.

Usando Player Prefs fuera del modo de juego

Muchas veces usamos la clase Player Prefs para guardar datos. Pero que pasa cuando queremos borrar los datos guardados?. Yo solia colocar e...