Skip to content

Instantly share code, notes, and snippets.

@dpid
Created May 3, 2017 19:21
Show Gist options
  • Save dpid/65465d98dd892322bfc95dda2cdafef0 to your computer and use it in GitHub Desktop.
Save dpid/65465d98dd892322bfc95dda2cdafef0 to your computer and use it in GitHub Desktop.
Unity C# utility class for making scriptable objects.
using UnityEngine;
using UnityEditor;
using System.IO;
public static class ScriptableObjectUtility
{
public static void CreateAsset<T>() where T : ScriptableObject
{
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
if (path != "" && Path.GetExtension(path) != "")
{
path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
}
CreateAssetAtPath<T>(path);
}
public static void CreateAssetAtPath<T>(string path, string filename = "") where T : ScriptableObject
{
T asset = ScriptableObject.CreateInstance<T>();
if (path == "")
{
path = "Assets";
}
else if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (filename == "")
{
filename = "New " + typeof(T).ToString() + ".asset";
}
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/" + filename);
AssetDatabase.CreateAsset(asset, assetPathAndName);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
EditorUtility.FocusProjectWindow();
Selection.activeObject = asset;
}
}
@dpid
Copy link
Author

dpid commented Mar 18, 2018

Example usage :

[MenuItem("Assets/Create/MyScriptableObject")]
public static void CreateScriptableObject()
{
	ScriptableObjectUtility.CreateAsset<MyScriptableObject>();
}

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