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. Dismiss Notice

Editor callback for Prefab Mode being open

Discussion in 'Prefabs' started by rfadeev, Oct 9, 2018.

  1. rfadeev

    rfadeev

    Joined:
    Oct 1, 2013
    Posts:
    21
    Hi,

    During Unite Berlin 2018 "Technical Deep Dive into the New Prefab System" talk there was a question about is there an editor callback for Prefab Mode being opened and whether it's possible to set prefab editor environments by code:


    The answer from Unity staff was "Yes to both". Could anybody please advise which class references should I take a look for details about that?
     
  2. Mads-Nyholm

    Mads-Nyholm

    Unity Technologies

    Joined:
    Aug 19, 2013
    Posts:
    215
    Hi,

    You will find the callbacks in the
    PrefabStage
    class (namespace:
    UnityEditor.Experimental.SceneManagement
    )

    Usage example:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.SceneManagement;
    3. using UnityEditor;
    4. using UnityEditor.Experimental.SceneManagement;
    5.  
    6.  
    7. [InitializeOnLoad]
    8. class CustomPrefabEnvironment
    9. {
    10.     static CustomPrefabEnvironment()
    11.     {
    12.         PrefabStage.prefabStageOpened += OnPrefabStageOpened;
    13.     }
    14.  
    15.     static void OnPrefabStageOpened(PrefabStage prefabStage)
    16.     {
    17.         Debug.Log("OnPrefabStageOpened " + prefabStage.prefabAssetPath);
    18.  
    19.         // Get info from the PrefabStage
    20.         var root = prefabStage.prefabContentsRoot;
    21.         var scene = prefabStage.scene;
    22.         var renderer = root.GetComponent<Renderer>();
    23.  
    24.         // If no renderer skip our custom environment
    25.         if (renderer == null)
    26.             return;
    27.  
    28.         // Create environment plane
    29.         var plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
    30.         SceneManager.MoveGameObjectToScene(plane, scene);
    31.  
    32.         // Adjust environment plane to the prefab root's lower bounds
    33.         Bounds bounds = renderer.bounds;
    34.         plane.transform.position = new Vector3(bounds.center.x, bounds.min.y, bounds.center.z);
    35.     }
    36. }
    37.  
     
    Last edited: Oct 20, 2020
  3. rfadeev

    rfadeev

    Joined:
    Oct 1, 2013
    Posts:
    21
    Great, thanks a lot for the detailed explanation!