Last active
June 19, 2021 04:30
-
-
Save ChrisDirkis/c1fd0de9dea4804c3fb07bc04f336368 to your computer and use it in GitHub Desktop.
CreateScriptableObjectInstance script (removes the need for [CreateAssetMenu] attribute)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using UnityEditor; | |
using UnityEngine; | |
namespace ChrisDirkis.Utility.Editor { | |
public class CreateScriptableObjectInstance : MonoBehaviour { | |
private const string MenuItemAddress = "Assets/Create/Scriptable Object Instance"; | |
private const int Priority = int.MaxValue; | |
[MenuItem(MenuItemAddress, priority = Priority)] | |
private static void Create() { | |
var selected = Selection.activeObject as MonoScript; | |
if (selected && typeof(ScriptableObject).IsAssignableFrom(selected.GetClass())) { | |
var newInstance = ScriptableObject.CreateInstance(selected.GetClass()); | |
var scriptPath = AssetDatabase.GetAssetPath(selected); | |
var assetPath = Path.Combine(Path.GetDirectoryName(scriptPath), $"New {selected.GetClass().Name}.asset"); | |
// if this path is taken, we search for a new one | |
var counter = 0; | |
while (AssetDatabase.LoadMainAssetAtPath(assetPath)) { | |
counter++; | |
assetPath = Path.Combine(Path.GetDirectoryName(scriptPath), $"New {selected.GetClass().Name} ({counter}).asset"); | |
} | |
AssetDatabase.CreateAsset(newInstance, assetPath); | |
Selection.activeObject = newInstance; | |
} | |
} | |
[MenuItem(MenuItemAddress, validate = true)] | |
private static bool Validate() { | |
var selected = Selection.activeObject as MonoScript; | |
return selected && typeof(ScriptableObject).IsAssignableFrom(selected.GetClass()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment