Unity3D – Custom classes appear on Inspector

Hi folks,

Long time no see.

 

Let me teach you something I’ve learned some time ago. In Unity3D, we can create a custom class and make it appear in Inspector, just like other classes like Transform and GameObject, just like this:

Screen Shot 2013-01-23 at 3.43.52 PM

 

 

 

 

 

 

 

 

 

 

 

 

But we can do more: let’s imagine a real game-programming situation: We’d like to implement an item shop in our game. So, basically, we need some information about this item like: name, description, image, price, whether it’s bought or not… So, we can wrap it all together now. Let’s stop talking and start:

 

First, create an empty Game Object. After, create a new C# script and name it “Shop”. Open it and lets start programming.

 

An empty class will seem like this:

 

Screen Shot 2013-01-23 at 4.01.20 PM

So, after the last right bracket, write this:

 

public class ShopItem

{

public string name;

public string description;

public Texture2D texture;

public int price;

public bool bought;

}

 

So, on the top of our script, right after public class Shop : Monobehaviour {, type

 

public List<ShopItem> shopItens;

 

To use Lists and Dictionarys, onde the top of our script, just use:

 

using System.Collections.Generic;

 

Now, drag this script to our empty Game Object and no custom parameters should appear yet. That’s because we didn’t tell Unity that our custom class need to be serialized. So, to serialize our custom class, just write this above ShopItem’s class:

 

[System.Serializable]

 

It now puts MetaData to the class which could be retrived by reflection and used by Unity. With this Unity knows that it should/can serialize the class.

 

Just come back to Unity and the public attribute ShopItens should appear, like this:

 

Screen Shot 2013-01-23 at 4.08.35 PM

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

That can be an easy way to give your project to Level Designer responsible or just to change/add/remove itens from your shop.

 

Thanks for all. Here’s the full script.

 

Screen Shot 2013-01-23 at 4.11.38 PM

 

Advertisements

Honey Castle In coming…

Olá pessoal! este é Bearnald!

Ele acaba de realizar seu maior sonho! Construir um castelo inteiro de puro MEL!!!

Mas tem um problema! ele construiu seu querido castelo no meio da floresta, agora todos os insetos estão malucos para devora-lo!!

Agora ele irá tomar as medidas necessárias e desnecessárias, para proteger seu SONHO!!!

Próximo game da OvertimeStudios está a caminho!!! Aguardem…