Unity: Scriptable objects

In this blog I will try to explain scriptable objects and an example of how to create them in Unity.

1. Introduction

When you read about Scriptable objects in internet you find that they are a way to store a large amount of data.

When you use a scriptable object it will not duplicate or copy the data, which is one of differences with others class and objects.

Also can be saved as asset and accesed by creating a submenu in the unity editor.

In the next part of the blog I will give an example of how to create a scriptable object

2. Scriptable object example

In the script folder create a script called “Item”, this script will be modified to work like a scriptable object

3. Creating a scriptable object

First: Create a sub menu in the Unity editor, with that sub-menu you can create scriptables objects as assets in Unity.

Second: Change the class of the script from Monobehaviour to ScriptableObject

Third: Create the properties of your scriptable object, in this example we use a image, a name and a description.

Remember save the changes to be applied in Unity

4. Using the sub-menu

Go to your folder and make rigth click on it, search for the name of the sub-menu we just created and select the option “item_generico”, this will create a new asset in your folder, a new scriptable object.

5. Set the properties of your scriptable object

Fill the properties we previously created in the scriptable object adding an image, a name and a description.

6. Create a script to let your scriptable object to be attached a gameobject

To attach a scriptable object to an object just create a script that work as bridge, this script will referenced the properties of the scriptable object like the name of the item and the sprite (image) of the item.

For my example , I named the script as “colec”.

7. Making everything work

Now in a game object add the script Colec we just create.

8. Finishing the scriptable object!!

When you add the script Colec to the object it will ask you for the scriptable object, once you have do it this the object will set the sprite, name from the scriptable object.

If you find this blog useful let us a comment, and follow us in our Instagram @tortugamedev and Twitter @Totuas2.

And don’t forget to check out the rest of the blogs!!

Leave a Comment

Your email address will not be published.