I have a Unity3D editor class that creates a new asset on the fly. Then I call AssetDatabase.Refresh using the default option (which is strongly recommended). Due to the fact that refreshing is an asynchronous way I need a way to get informed when refreshing is ready.
Background:
I wrote a code generator that creates a C# script. It is meant to create a helper component for the active game object in the scene. Everything works fine so far, the file is created by methods from System.File.IO. Now I want to add the newly created MonoBehaviour to the active game object automatically.
Current status / limiting factors:
- As expected all active objects are destroyed during the refresh process. This makes it impossible to work with any standard polling approach like invoke or coroutines as they terminate when the game object is destroyed.
- Polling is in general no good solution, but would be alright in this case. On the other hand I don't want to use threads as this is not recommended in Unity.
- static constructors are called immediately after refreshing is ready if their class has the InitializeOnLoadAttribute set or if the component is referred in the active scene.
Possible (cumbersome) way that might work:
- Define a class
ActionAfterRefreshthat contains meta information and code to perform after a refresh e.g. class name to load and code to perform anAddComponentfor it in constructor. - Serialise this class as JSON file in a special cache directory
- Define a class
Loaderhaving a static constructor that:- Looks if there is a matching JSON file in the cache directory. If so, create an instance and execute the code
- Delete JSON file
I think this could work and I guess you know why I wrote cumbersome. Is there any smarter, better, faster way to achieve this? Did I overlook the live saving OnRefreshDatabaseReady event?
Thanks for your help