In a melting weather, here in Antalya, i’ m writing the second post of my new series on Serializable Objects.
For those, who hasn’t seen the first post, you might find the first post here.
This second post of the series aims giving some brief information on Scriptable Objects, how you use them in the code and in a Unity project. Please fasten your seatbelts as we’ re diving into some technical details 🙂
Serializable Object Implementation
To be able to use Serializable Object, you have to create a child class of Scriptable Object. This class will be able to receive the unity callbacks that’s scriptable objects can. See the image below for a basic structure of a Scriptable Object:
(For more detailed information follow this link)
Create Instance of a Scriptable Object
There are two ways to create instance of a Scriptable Object:
Similar with MonoBehaviours, Scriptable Objects instance should not create with “new” keyword. This prevents call of the unity callbacks and causes undesired results in the code flow.
That’ s why you have to create an instance of a Scriptable Object with CreateInstance static method defined in the Scriptable Object.
You can find the documentation of CreateInstance method here.
Below you can see the example usage of CreateInstance overloads:
Because CreateInstance returns a ScriptableObject, you may have to cast to the desired class.
2- Creating an asset file of a Scriptable Object
Creating an asset file of a Scriptable Object requires “CreateAssetMenu” attribute to be defined for the class. See the image below:
After you add this property, you’ ll be see a button in the context menu(right click menu) in Project window as follows:
When you press the create button, you’ ll see a new asset file created in the project.
This asset file a serialized version of our scriptable object and be able to store data in it. It also can have logic in it(I’ ll share some more details in the coming posts on this.)
After creating the file, you might reference it to a monobehaviour which has the required field definition:
Now the variable in the AMonoBehaviour class is initialized(by the Unity Serialization), thus, you can use it in your code.
That’ s how you can create an instance of a Scriptable Object with two different ways and use them.
Both of them has it’s own pros and cons. I’ll share some more detailed information on different use-cases of Scriptable Object in the coming posts.
Bye for now 😎😊