domingo, 22 de mayo de 2016

Custom Classes

Versión en Español

Analyzing the frequently asked questions in the forums and because after we learn to use arrays and lists, we want to solve all our problems with them, it becomes difficult and messy to manage indexes and our code is not as clean as we would like and bidimentional arrays are even more complicated. I want to teach you an alternative, custom classes, with them, we can handle many values and can give them many uses, in this case I want to teach them with a very basic example, the main idea is understand them first.

What I mean by custom class?

A custom class is very common in the world of programming, is any class that doesn't come with default language, but for people who are not completely familiar with object-oriented languages or as I, that started using Unity before learning to program completely, it is a bit complicated, for example, I thought that all classes should inherit from MonoBehaviour. A custom class is as easy as this:
public class CustomClass {
    public int Integer1;
    public string String1;
}
However, by not inherit from MonoBehaviour we lose some advantages such as the possibility of being added as component to GameObjects, methods that are automatically called, such as Start, Update, Awake, etc., among many others, but also we have other advantages such as the ability to serialize (I'll explain this in another post later), also it makes them much more optimized when having a large class hierarchy as is the case of a complex inventory and other advantages that I will cover in following entries.

Display values of custom classes in the Unity inspector

Custom classes can't be added as components to GameObject, so we don't get to see them in the inspector, even if we make a variable in a MonoBehaviour with the type of our class they won't be displayed, let's see an example:
using UnityEngine;
using System.Collections;

public class CustomClassesTutorial : MonoBehaviour { 
    public Item TestItem;
}

public class Item {
    public int Id;
    public int price;
    public Sprite Image;
}
By adding this script to a GameObject in Unity we see the following:
As shown in the picture, Item type variable is not visible in the inspector, this can be fixed only by adding the attribute [System.Serializable] before declaring class or adding up "using System;" and then only using [Serializable]:
using UnityEngine;
using System.Collections;

public class CustomClassesTutorial : MonoBehaviour { 
    public Item TestItem;
}

[System.Serializable]
public class Item {
    public int Id;
    public int price;
    public Sprite Image;
}
And this results in :
As you can see now, the inspector displays the attributes of the Item class. Well, now that we know what is a custom class, how to create them and display them in the inspector, in my next post we will go through an example where we can truly appreciate their uses.

No hay comentarios:

Publicar un comentario