Search Unity

Smart but ugly trick to create ScriptableObject.

Discussion in 'Scripting' started by Mockarutan, Oct 22, 2014.

  1. Mockarutan

    Mockarutan

    Joined:
    May 22, 2011
    Posts:
    159
    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!

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEditor;
    4. using System.IO;
    5. using System.Reflection;
    6. using System;
    7.  
    8. public class ScriptableObjectUtility : ScriptableObject
    9. {
    10.     [MenuItem("Utilities/Create Scriptable Object")]
    11.     public static void CreateAsset()
    12.     {
    13.         if (Selection.activeObject is MonoScript)
    14.         {
    15.             MonoScript script = Selection.activeObject as MonoScript;
    16.             string typeName = script.name;
    17.  
    18.             foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
    19.             {
    20.                 if (type.ToString().Equals(typeName) && type.IsSubclassOf(typeof(ScriptableObject)))
    21.                 {
    22.                     CreateScriptableObject(type);
    23.                     return;
    24.                 }
    25.             }
    26.         }
    27.     }
    28.  
    29.     public static void CreateScriptableObject(Type type)
    30.     {
    31.         UnityEngine.Object asset = (UnityEngine.Object)ScriptableObject.CreateInstance(type);
    32.  
    33.         string path = AssetDatabase.GetAssetPath(Selection.activeObject);
    34.         if (path == "")
    35.         {
    36.             path = "Assets";
    37.         }
    38.         else if (Path.GetExtension(path) != "")
    39.         {
    40.             path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
    41.         }
    42.  
    43.         string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + type.ToString() + ".asset");
    44.  
    45.         AssetDatabase.CreateAsset(asset, assetPathAndName);
    46.  
    47.         AssetDatabase.SaveAssets();
    48.         AssetDatabase.Refresh();
    49.         EditorUtility.FocusProjectWindow();
    50.         Selection.activeObject = asset;
    51.     }
    52. }
     
  2. guavaman

    guavaman

    Joined:
    Nov 20, 2009
    Posts:
    5,633
  3. Mockarutan

    Mockarutan

    Joined:
    May 22, 2011
    Posts:
    159
    guavaman likes this.