Getting generated MonoScript class with AssetPostprocessor

Hello all, I’m trying to generate code with Editor scripts to create MonoBehaviour classes. I’m using an AssetPostprocessor class to get a callback when the MonoScript file is imported. From within that callback I’d like to create a GameObject in my scene and add on it the MonoBehaviour in the imported MonoScript. Now it seems to work up to the point where I get the MonoScript asset with AssetDatabase.LoadAssetAtPath. When I call monoScript.GetClass(), it returns null. I’m guessing the MonoScript file is found but the actual type contained in it isn’t “loaded” yet?

Is it possible to do what I’m trying to do? Here’s my code when I get the callback from AssetPostprocessor :

AssetDatabase.ImportAsset( _assetPath );
MonoScript script = AssetDatabase.LoadAssetAtPath<MonoScript>( _assetPath );
if (script != null)
{
    GameObject sceneGO = new GameObject( );

    //this line debugs "AddComponent asking for invalid type" because script.GetClass() returns null
    sceneGO.AddComponent( script.GetClass() );
}

Well, if the script was just created then it isn’t compiled yet, so you won’t be able to use the code in it before it gets compiled and the whole Unity AppDomain reloads with the newly generated .Net assemblies. Only then you will be able to use the script.

See this answer, it may help you with ideas how to do that: c# - Notification when AssetDatabase.Refresh is ready - Stack Overflow

Note that instances of ScriptableObject derived classes with their hideFlags set to HideFlags.HideAndDontSave will also survive the AppDomain reloading, so you can use that to “schedule” your action to happen after the reloading (and then make sure to destroy that object).

Thanks @Flipbookee that will possibly solve my issue. I thought loading commands from a file or ScriptableObject could be the solution but I would’nt have gone with this approach if there was another way to do it. I guess I’ll get into it today!

1 Like