Event for loading component in the editor

Is there an event/callback for gameobjects/components that are loaded in a scene?
All of this applies to editor time only, NOT during playmode or runtime.

I want to monitor a specific component type (“PhotonView”) and need to check this type whenever it is loaded in a scene for the first time:

  • when a scene is loaded
  • whenever it is created in the scene (i.e. by duplicating a object with a PhotonView attached or by simply adding the component)

Is there some sort of “OnLoaded”/“OnCreated” method that I can use for my components?
I believe that if there is a solution, it is probably not in the public API, but I’m fine with a non documented solution.

2 Answers

2

executeInEditMode can sometimes be undesirable.

In that case you will need to open a pandora box and look into:

ISerializationCallbackReceiver (1-2 functions called when object is created or loaded/saved)

and into an approach discussed here (perhaps with some core singleton that already existed prior to your object birth, and will process its request next frame after your object is created/deserialized):

https://forum.unity3d.com/threads/update-class-in-editor-but-not-when-playing.484647/

Also, I would argue that it would be acceptable to declare an actual constructor in a Monobehavior, register for an update from EditorApplication and process query NEXT time update is ran for you.

like this:
#if UNITY_EDITOR
//DONT DO ANYTHING IN CONSTRUCTOR EXCEPT CALLBACK SIGN-UP
public MyMonobehaviorClass(){
//since constructor is called multiple times, important to unsubscribe then re-subscribe, to avoid duplicates:
      EditorApplication.update -= myOneTimeUpdate;
      EditorApplication.update += myOneTimeUpdate;
}

void myOneTimeUpdate(){
     //we were bourn! PRocess, then unsubscribe
     EditorApplication.update -= myOneTimeUpdate;
}
#endif

Interesting little toolet you found there! the Link. I'm going to have to play with that. Upvoted for giving me new data.

I’d use the [ExecuteInEditMode] attribute on the monobehavior and then put my code in Awake(). Now this would still be called during playmode so I’d check that Application.isPlayingis false before. Something like this.

[ExecuteInEditMode]
public class Foo : MonoBehavior{  
    void Awake()
    {
        if(!Application.isPlaying)
            bar();
    }
}

So [ExecuteInEditMode] is placed before the class only? may be why i was getting error LOL. Don't fully understand it's usage personally.