Problem with ScriptableObject and Custom Editor

I have written an editor script that generates a custom .asset file. The asset file is created using a ScriptableObject and then sub-assets are added using AssetDatabase.AddObjectToAsset.

I would like to add an inspector GUI that is shown when the asset file is selected. For some reason the inspector GUI is not showing up when the asset file is selected. Instead I have to expand the asset file in project panel and then select the the same asset name again.

1198-screeny.png

[CustomEditor(typeof(TestAsset))]
public class TestAssetEditor : UnityEditor.Editor {

    public override void OnInspectorGUI() {
        if (GUILayout.Button("Test"))
            Debug.Log("TEST");
    }

    [MenuItem("Test/Test")]
    public static void Test() {
        Object asset = ScriptableObject.CreateInstance<TestAsset>();
        asset.name = "Test Name";
        AssetDatabase.CreateAsset(asset, "Assets/Test.asset");

        Mesh test = new Mesh();
        test.name = "test_mesh";
        test.vertices = new Vector3[] {
            new Vector3(0, 0, 0),
            new Vector3(0, 1, 0),
            new Vector3(1, 1, 0)
        };
        test.uv = new Vector2[] {
            new Vector2(0, 0),
            new Vector2(0, 1),
            new Vector2(1, 1)
        };
        test.triangles = new int[] { 0, 1, 2 };

        test.RecalculateNormals();

        AssetDatabase.AddObjectToAsset(test, asset);

        AssetDatabase.ImportAsset("Assets/Test.asset");
    }

}

[System.Serializable]
public class TestAsset : ScriptableObject {

    public int test = 0;

    

}

After an e-mail conversation with Unity support it appears that this is in fact a bug with Unity.

Whilst there are no immediate side effects to implanting assets into a “.prefab” file this is not recommended because other Unity functionality might assume that a prefab file only contains a prefab. Additionally future changes to the way in which prefabs are stored might cause added assets to become corrupt or lost.

So until this bug gets fixed the only solution is to expand the asset file and select the ScriptableObject. Not perfect but this is at least a workable solution for now.

Actually, there is a “workaround” for this. Create an inspector which works on Object - in the OnEnable see if the target is a valid asset, and use LoadAllAssetRepresentationsAtPath to find the one you’re interested in, and then call the inspector GUI for your one in the OnInspectorGUI.