Writer, Choreographer, Game Developer

Creating ScriptableObjects in Unity

Posted on

This is a short editor script that I use for creating instances of ScriptableObject classes in the Unity editor. Most scripts that create ScriptableObjects require you to add new code for each object type. This script does not. Select any class that extends ScriptableObject and choose Create->Instance to create an instance of that class.

using UnityEngine;
using UnityEditor;
using System.IO;

public static class ScriptableObjectCreator {
  [MenuItem( "Assets/Create/Instance" )]
  public static void CreateInstance() {
    foreach( Object o in Selection.objects ) {
      if( o is MonoScript ) {
        MonoScript script = (MonoScript)o;
        System.Type type = script.GetClass();
        if( type.IsSubclassOf( typeof( ScriptableObject ) ) ) {
          CreateAsset( type );
        }
      }
    }
  }

  [MenuItem( "Assets/Create/Instance", true )]
  public static bool ValidateCreateInstance() {
    foreach( Object o in Selection.objects ) {
      if( o is MonoScript ) {
        MonoScript script = (MonoScript)o;
        System.Type type = script.GetClass();
        if( type.IsSubclassOf( typeof( ScriptableObject ) ) ) {
          return true;
        }
      }
    }
    return false;
  }

  private static void CreateAsset( System.Type type ) {
    var asset = ScriptableObject.CreateInstance( type );
    string path = AssetDatabase.GetAssetPath( Selection.activeObject );
    if( path == "" )  {
      path = "Assets";
    } else if( Path.GetExtension( path ) != "" ) {
      path = path.Replace( Path.GetFileName( AssetDatabase.GetAssetPath( Selection.activeObject ) ), "" );
    }
    string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath( path + "/New " + type.ToString() + ".asset" );
    AssetDatabase.CreateAsset( asset, assetPathAndName );
    AssetDatabase.SaveAssets();
    EditorUtility.FocusProjectWindow();
    Selection.activeObject = asset;
  }
}

To use the script, just add it to a folder called "Editor" inside your Unity assets folder.

The script isn't as sophisticated as ScriptableObject Factory but I prefer it because it is quicker to use - just right click on a class and choose Create->Instance.


Also in the collection Unity Game Engine