Smart but ugly trick to create ScriptableObject.

Just wrote this tired of the “no way to create a ScriptableObject in a good way” problem. It’s not really pretty and it might have some unsafe aspects, but it’s straight forward to create the ScriptableObjects with it.

Just mark the ScriptableObjects script and press the “Create Scriptable Object” under “Utilities”.

Please feel free to point out flaws or improvements!

using UnityEngine;
using UnityEditor;
using System.IO;
using System.Reflection;
using System;

public class ScriptableObjectUtility : ScriptableObject
{
    [MenuItem("Utilities/Create Scriptable Object")]
    public static void CreateAsset()
    {
        if (Selection.activeObject is MonoScript)
        {
            MonoScript script = Selection.activeObject as MonoScript;
            string typeName = script.name;

            foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (type.ToString().Equals(typeName) && type.IsSubclassOf(typeof(ScriptableObject)))
                {
                    CreateScriptableObject(type);
                    return;
                }
            }
        }
    }

    public static void CreateScriptableObject(Type type)
    {
        UnityEngine.Object asset = (UnityEngine.Object)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 + type.ToString() + ".asset");

        AssetDatabase.CreateAsset(asset, assetPathAndName);

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

There’s this one too: http://wiki.unity3d.com/index.php?title=CreateScriptableObjectAsset
I like how you’ve implemented creating the script by selecting a MonoScript first.

I started with that one but i don’t like to write code for every different type I want to create :slight_smile:

1 Like