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 [Serialize Reference] is crashing unity

Discussion in 'Scripting' started by Scott_Ewing_8, Mar 31, 2024.

  1. Scott_Ewing_8


    Jan 8, 2020
    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.

    Code (CSharp):
    1. [SerializeReference] Type _type;
    3.        private void Start() {
    5.            if (TryGetComponent(_type, out var component)) {
    6.                print ("Found component");
    7.            }
    8.            else {
    9.                print("Did not find component");
    10.            }
    11.        }
    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:

    Code (csharp):
    1. NotSupportedException: Specified method is not supported.
    2. System.RuntimeType .. ctor() at <e40e5a8f982c4b618a930d29f9bd091c>:0
    3. 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
  2. spiney199


    Feb 11, 2021
    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.
    Spy-Master likes this.
  3. Ryiah


    Oct 11, 2012
    Use Component. It's the base type for everything that can attach to a GameObject.
    Spy-Master likes this.
  4. Spy-Master


    Aug 4, 2022
    Fun fact, Addressables has a SerializedType struct.
    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.
    You could probably cut these out along with SerializedType’s property drawer.
    Alex-Chouls, Ryiah and spiney199 like this.