Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Getting generated MonoScript class with AssetPostprocessor

Discussion in 'Editor & General Support' started by DoomSamurai, Nov 2, 2015.

  1. DoomSamurai

    DoomSamurai

    Joined:
    Oct 10, 2012
    Posts:
    159
    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 :
    Code (CSharp):
    1.  
    2. AssetDatabase.ImportAsset( _assetPath );
    3. MonoScript script = AssetDatabase.LoadAssetAtPath<MonoScript>( _assetPath );
    4. if (script != null)
    5. {
    6.     GameObject sceneGO = new GameObject( );
    7.  
    8.     //this line debugs "AddComponent asking for invalid type" because script.GetClass() returns null
    9.     sceneGO.AddComponent( script.GetClass() );
    10. }
    11.  
     
  2. Flipbookee

    Flipbookee

    Joined:
    Jun 2, 2012
    Posts:
    2,751
    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: http://stackoverflow.com/questions/23795173/notification-when-assetdatabase-refresh-is-ready

    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).
     
  3. DoomSamurai

    DoomSamurai

    Joined:
    Oct 10, 2012
    Posts:
    159
    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!
     
    Flipbookee likes this.