ScriptableObject Factory – Create Any ScriptableObject Type

A ScriptableObject is a serializable Unity object that is not attached to a GameObject (like MonoBehaviours are). They are typically used for storing data and they can also be saved as an asset file in you project, just like any other texture or audio clip.

If you’re not familiar with them be sure to check out this video: Introduction to Scriptable Objects.

The helper script in this post is available as a .unitypackage here: UnityPackage

Creating a ScriptableObject

Most code samples that describe how to create a new Scriptable object repeat the same boring, boilerplate code that looks something along the lines of:

var obj = ScriptableObject.CreateInstance();
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/" + "assetName.asset");
AssetDatabase.CreateAsset (asset, assetPathAndName);

AssetDatabase.SaveAssets ();
EditorUtility.FocusProjectWindow ();
Selection.activeObject = asset;

Unfortunately, there’s no built-in option to create one from the editor…

The little recipe here actually performs the same code as above, including adding a menu item to the editor, but it only works for a single class type, so you’d have to append it with more code for every new type you’d like to instantiate.

ScriptableObjectFactory

I’ve put together a short editor extension that will look for all ScriptableObject types in your project and let you select which one you want to create.

This extension adds a new menu option under Assets/Create or Project/Create:

Create a ScriptableObject

Create a ScriptableObject

 

 

 

 

 

 

 

 

 

 

 

 

Create a ScriptableObject

Create a ScriptableObject

 

 

 

 

 

 

 

 

 

 

 

 

 

Once you click this option, a popup window opens and allows you to select what type of object you want to create:

Popup for creating a ScriptableObject

Popup for creating a ScriptableObject

 

 

 

 

 

The source code for this little helper is available at: ScriptableObjectFactory.

It’s also available as a .unitypackage here: UnityPackage

Enjoy 🙂

Resources

This entry was posted in Unity and tagged , , , . Bookmark the permalink.