is there a script for creating ScriptableObjects by context menu?
I know there is [CreateAssetMenu(menuName = “”)] but it’s awkward to use it on every ScriptableObject.
Instead I want to create an contextmenu Item that can generate all ScriptableObjects.
You would have to be more specific because CreateAssetMenu allows you to generate all your ScriptableObjects, one by one.
If you want to generate more than one at once, using a combination of MenuItem (Scripting API) and ScriptableObject.CreateInstance (Scripting API) might be an idea.
k ty, I’ll post my solution when I finished it.
here we go:
[MenuItem("myFunctions/CreateScriptableObject")]
public static void createScriptableObject()
{
if (Selection.activeObject is MonoScript)
{
MonoScript ms = (MonoScript)Selection.activeObject;
ScriptableObject so = ScriptableObject.CreateInstance(ms.name);
string path = System.IO.Directory.GetParent(AssetDatabase.GetAssetPath(ms.GetInstanceID())) + "/" + ms.name + ".asset";
int cntr = 0;
while (!createIfDoesntExists(path, so))
{
path = System.IO.Directory.GetParent(AssetDatabase.GetAssetPath(ms.GetInstanceID())) + "/" + ms.name + cntr.ToString() + ".asset";
cntr++;
if (cntr > 10)
{
break;
}
}
AssetDatabase.Refresh();
}
}
public static bool createIfDoesntExists(string path, Object o)
{
var ap = AssetDatabase.LoadAssetAtPath(path, o.GetType());
if (ap == null)
{
AssetDatabase.CreateAsset(o, path);
return true;
}
else
{
return false;
}
}
any improvements?
You have to select the ScriptableObject source file and then you can add it by the MenuItem
1 Like
tyoden
5
If google brought you here, like me, then here is an improved script for the context menu
using UnityEditor;
public static class ScriptableObjectCreator
{
[MenuItem("Assets/Create/Scriptable Object", false, 0)]
public static void CreateScriptableObject()
{
var selection = Selection.activeObject;
var assetPath = AssetDatabase.GetAssetPath(selection.GetInstanceID());
var path = $"{System.IO.Directory.GetParent(assetPath)}/{selection.name}.asset";
ProjectWindowUtil.CreateAsset(ScriptableObject.CreateInstance(selection.name), path);
}
[MenuItem("Assets/Create/Scriptable Object", true)]
public static bool CreateScriptableObjectValidate()
{
return Selection.activeObject is MonoScript monoScript && IsScriptableObject(monoScript.GetClass());
}
private static bool IsScriptableObject(System.Type type) => typeof(ScriptableObject).IsAssignableFrom(type);
}
}