Search Unity

Work out with ISerializationCallbackReceiver if MonoBehaviour is on Prefab or not?

Discussion in 'Prefabs' started by tom_e_roberts, Apr 16, 2019.

  1. tom_e_roberts

    tom_e_roberts

    Joined:
    Jul 19, 2017
    Posts:
    29
    I'm currently trying to work out on save if a MonoBehaviour being serialised is a prefab or not, here's an example of what I'm trying to do:
    Code (CSharp):
    1. public class Sync : MonoBehaviour, ISerializationCallbackReceiver
    2. {
    3.     [SerializedField] private bool m_isPrefab;
    4.  
    5.     void ISerializationCallbackReceiver.OnBeforeSerialize()
    6.     {
    7. #if UNITY_EDITOR
    8.         if (!UnityEditor.EditorApplication.isPlaying)
    9.         {
    10.             m_isPrefab = UnityEditor.SceneManagement.EditorSceneManager.IsPreviewScene(gameObject.scene) ||
    11.                     UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) ||
    12.                     (UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage()?.IsPartOfPrefabContents(gameObject) ?? false);
    13.         }
    14. #endif
    15.     }
    16.  
    17.     void ISerializationCallbackReceiver.OnAfterDeserialize()
    18.     {
    19.     }
    20. }
    But right not this doesn't work on saving the asset, it saves them outside the preview scene so that returns false and when saving it seems to not be flagged as part of a Prefab asset.

    Is this the intended behaviour?
    Any one have ideas on how to check this?

    Has to be somewhat light as it could be on many objects at once
     
  2. tom_e_roberts

    tom_e_roberts

    Joined:
    Jul 19, 2017
    Posts:
    29
    Never mind I fixed this pretty quickly after posting (the usual with coding)

    Code (CSharp):
    1. m_isPrefab = UnityEditor.SceneManagement.EditorSceneManager.IsPreviewScene(gameObject.scene) ||
    2.                         UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) || !gameObject.scene.IsValid()
    When saving the asset, the prefab isn't in any scene, so the scene isn't valid, add that and it seems to be working quite well