Search Unity

PrefabUtility and ISerializationCallbackReceiver Strangeness

Discussion in 'Editor & General Support' started by redwren, Oct 22, 2019.

  1. redwren

    redwren

    Joined:
    Aug 2, 2019
    Posts:
    69
    I'm trying to get to the bottom of some strange behavior inside a custom serialization callback. Here's my test class:

    Code (CSharp):
    1. using UnityEditor;
    2. using UnityEngine;
    3.  
    4. public class SerializationCallbackTest : MonoBehaviour, ISerializationCallbackReceiver {
    5.    
    6.     [SerializeField] private string _prefabAssetType = "default";
    7.     [SerializeField] private string _prefabInstanceStatus = "default";
    8.    
    9.     public void OnBeforeSerialize() {
    10.         #if UNITY_EDITOR
    11.         _prefabAssetType = PrefabUtility.GetPrefabAssetType(this).ToString();
    12.         _prefabInstanceStatus = PrefabUtility.GetPrefabInstanceStatus(this).ToString();
    13.         #endif
    14.     }
    15.  
    16.     public void OnAfterDeserialize() {
    17.        
    18.     }
    19. }
    Pretty simple stuff. This started because I was trying to make some properties of a script instance only; I don't want them serialized into the prefab assets. When that class is first placed on a game object in the scene, the two properties are serialized into the scene file as "NotAPrefab" like I would expect.

    It gets strange when I drag the object into the library to create a prefab. The prefab file is serialized with "NotAPrefab" for both fields. But when the prefab is inspected in the editor, the asset type is "Regular" and the instance status is "NotAPrefab". Can anyone explain what's going on? Any suggestions for how to reliably change the serialization for prefab assets, but not instances?

    Using 2019.1.14.
     
  2. redwren

    redwren

    Joined:
    Aug 2, 2019
    Posts:
    69
    After more experimentation, I found that EditorUtility.IsPersistent is true for prefab assets during serialization. Any input on why that would work as expected, but none of the PrefabUtility checks?