Search Unity

[InitializeOnLoad] Methods called before serialization?

Discussion in 'Immediate Mode GUI (IMGUI)' started by Dark-Protocol, Jan 9, 2017.

  1. Dark-Protocol

    Dark-Protocol

    Joined:
    Nov 19, 2011
    Posts:
    279
    I need to make a simple editor script that goes through all components of certain type in the scene and adds them to an array based on their properties upon load.

    I used the [InitializeOnLoad] attribute - https://docs.unity3d.com/ScriptReference/InitializeOnLoadAttribute.html but the constructor seems to be called before Unity's serialization takes place and therefore all components have their default property values set so I can't really sort them.

    I also added subscribed to sceneLoaded event in the static constructor of my class:
    UnityEditor.SceneManagement.EditorSceneManager.sceneLoaded += OnSceneLoaded;

    And this also doesn't seem to work - I switch scenes and the OnSceneLoaded doesn't get called.

    Any tips on how to work around that?

    Thanks!
     
    Novack likes this.
  2. Izzy2000

    Izzy2000

    Joined:
    Dec 18, 2013
    Posts:
    49
  3. Dark-Protocol

    Dark-Protocol

    Joined:
    Nov 19, 2011
    Posts:
    279
  4. Dark-Protocol

    Dark-Protocol

    Joined:
    Nov 19, 2011
    Posts:
    279
    After trying all sorts of things I came to the conclusion that InitializeOnLoad is just called before serialization and there's no way to make it wait or to call another method after serialization takes place so what I did was:

    Used InitializeOnLoad to get all objects of that certain type without filtering them, then subscribed to the onSceneGUIDelegate event and in it I filter the objects.
     
    Novack likes this.
  5. Izzy2000

    Izzy2000

    Joined:
    Dec 18, 2013
    Posts:
    49
    that callback might actually be called more than once per frame. See if you can use the Update callback, which should be called just once per frame, if not mistaken.
     
  6. Dark-Protocol

    Dark-Protocol

    Joined:
    Nov 19, 2011
    Posts:
    279
    Thanks! I'm aware that this callback is called several times for the different UI events but I need it to draw the discovered objects anyway so I have to stick with it.
     
    Izzy2000 likes this.