Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Callback on prefab instance creation via drag/drop?

Discussion in 'Prefabs' started by VRARDAJ, May 6, 2024.

  1. VRARDAJ

    VRARDAJ

    Joined:
    Jul 25, 2017
    Posts:
    54
    I'm building an editor tool in which a type of prefab gets autogenerated. The user should rarely need to instance this prefab manually, but since it's a prefab, they have the ability to do so at any time.

    Since this tool needs to maintain a reference to the current scene in which the prefab is instantiated, I would like to refresh that reference automatically in the background any time the user instantiates a new copy of it.

    The reference-to-be-refreshed is held in a scriptable object that is easy to update if I can consume a callback whenever the user instantiates the prefab via drag/drop from project view to hierarchy. Obviously, when they instance the prefab procedurally through the tool's UI, I can create my own callback, but when they drag/drop on their own instance, I need notification.

    I've tried the Reset() callback in any script within the prefab, which doesn't execute on instantiation. I've tried PrefabUtility.prefabInstanceUpdated, which also doesn't execute on instantiation. I've seen AssetPostprocessor.OnPostProcessAllAssets() as a suggestion, but that doesn't deal with instances, only assets.

    The only idea I have left is EditorApplication.hierarchyChanged, which feels wrong because I'd scan EVERY hierarchy change just in case one of them is a certain prefab instantiation. I'm hoping there's a more efficient way to generate the callback.

    Anyone have ideas I've overlooked?
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,159
    I think this is where you want to use the object change event API: https://docs.unity3d.com/ScriptReference/ObjectChangeEvents.html

    The docs have no example, but there's an example from ol' mate Karl here: https://forum.unity.com/threads/edi...n-by-user-or-user-script.788792/#post-8263803

    Yes the API is... weird as well

    But the
    ObjectChangeEventStream.GetCreateGameObjectHierarchyEvent
    should be fired when a prefab (or any game object) is created in a scene. Should be simple to listen for the right prefab via this method.
     
  3. VRARDAJ

    VRARDAJ

    Joined:
    Jul 25, 2017
    Posts:
    54
    Coooooooooool. Exactly the top-secret trick I was looking for. Thanks!
     
    spiney199 likes this.