Skip to content

Instantly share code, notes, and snippets.

@shayded-exe
Last active September 4, 2020 15:12
Show Gist options
  • Save shayded-exe/2be3d01df2edcdf69116 to your computer and use it in GitHub Desktop.
Save shayded-exe/2be3d01df2edcdf69116 to your computer and use it in GitHub Desktop.
Put this script in your Editor folder. Then right click on any inspector field that accepts a ScriptableObject to create an asset for it. The asset will also automatically be assigned to the field.
using System;
using System.IO;
using System.Linq;
using System.Linq.Extensions;
using UnityEditor;
using UnityEngine;
namespace PachowStudios.BadTummyBunny.Editor
{
[CustomPropertyDrawer(typeof(ScriptableObject), true)]
public class ScriptableObjectPropertyDrawer : PropertyDrawer
{
private SerializedProperty Property { get; set; }
private Type[] PossibleTypes
{
get
{
return fieldInfo.FieldType == typeof(ScriptableObject)
? new [] { typeof(ScriptableObject) }
: AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(fieldInfo.FieldType.IsAssignableFrom)
.ToArray();
}
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Property = property;
EditorGUI.PropertyField(position, property, label);
var clickEvent = Event.current;
if (clickEvent.type == EventType.MouseDown
&& clickEvent.button == 1
&& position.Contains(clickEvent.mousePosition))
{
clickEvent.Use();
EditorUtility.DisplayCustomMenu(
new Rect(clickEvent.mousePosition, Vector2.zero),
PossibleTypes.Select(t => new GUIContent(string.Format("Create {0} Asset", t.Name))).ToArray(),
-1, OnCreateAssetClick, null);
}
}
private void OnCreateAssetClick(object userData, string[] options, int selected)
{
if (selected >= 0)
CreateAsset(PossibleTypes[selected]);
}
private void CreateAsset(Type type)
{
var fileName = type.ToString().Split('.').Last();
var asset = ScriptableObject.CreateInstance(type);
var path = AssetDatabase.GetAssetPath(Selection.activeObject);
path = path.IsNullOrEmpty()
? "Assets/Resources"
: Path.GetDirectoryName(path);
path = AssetDatabase.GenerateUniqueAssetPath(string.Format("{0}/{1}.asset", path, fileName));
AssetDatabase.CreateAsset(asset, path);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
EditorUtility.FocusProjectWindow();
Selection.activeObject = asset;
fieldInfo.SetValue(Property.serializedObject.targetObject, asset);
}
}
}
@bellicapax
Copy link

I'm not sure what System.Linq.Extensions is, but my compiler could not find that namespace, so I just replaced line 60:

path = path.IsNullOrEmpty()

with

path = string.IsNullOrEmpty(path)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment