[Serialize Reference] is crashing unity

I want to let the user pick a type in the inspector, and then check if the game object has a component of that Type. This is the code I have.

[SerializeReference] Type _type;
      
       private void Start() {
          
           if (TryGetComponent(_type, out var component)) {
               print ("Found component");
           }
           else {
               print("Did not find component");
           }
       }

If Enter Play Mode Options is checked and Reload Domain / Reload Scene are unchecked in project settings then this code works (i.e i get the “Found Component message”). But when I exit play mode I get this error in the console log:

NotSupportedException: Specified method is not supported.
System.RuntimeType .. ctor() at <e40e5a8f982c4b618a930d29f9bd091c>:0
EditorApplication.Internal_CallGlobalEventHandler()

When I try to enter playmode again unity crashes. (Sometimes when I exit playmode its crashes imediatelly.)

The error and crash only happens if I have selected a type in the inspector. If it is left null there is no crash.

Finally if Enter Play Mode Options is unchecked the unity just crashed when entering play mode

Any help is appreciated

I have a feeling you’re probably using Odin. To that end: Do note use SerializeReference on System.Type!

If you want to serialize System.Type, you will need some other means to serialize it, such as Odin serialisation.

1 Like

Use Component. It’s the base type for everything that can attach to a GameObject.

1 Like

Fun fact, Addressables has a SerializedType struct.
https://docs.unity3d.com/Packages/com.unity.addressables@1.21/api/UnityEngine.ResourceManagement.Util.SerializedType.html
Conveniently, there’s also SerializedTypeRestrictionAttribute for constraining which types can be assigned, though the validation probably only functions for property assignment in the editor and not when evaluating something that’s been deserialized.
https://docs.unity3d.com/Packages/com.unity.addressables@2.0/api/UnityEngine.ResourceManagement.Util.SerializedTypeRestrictionAttribute.html
You could probably cut these out along with SerializedType’s property drawer.

3 Likes