Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Discussion Custom attribute for serialize Interface

Discussion in 'Editor & General Support' started by khalish260303, Apr 22, 2024.

  1. khalish260303

    khalish260303

    Joined:
    Nov 4, 2021
    Posts:
    13
    I want to create a custom attribute for serialize an interface to the inspector. So far, I already show the object field with type of interface to the inspector, but if I drag and drop a component to that field I got an error that say "InvalidOperationException: Cannot assign an object deriving from UnityEngine.Object to a managed reference. This is not supported". Anyone know how to solve this problem?
     

    Attached Files:

  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    7,263
    You cannot solve this problem. Interfaces cannot be dragged onto Inspector references.

    Instead, make a base class that implements the interface, or just rely on the base class. And add the [SerializeReference] attribute to the field, otherwise deserialization will fail.
     
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,647
    OP, if you're going to post code, use code tags and not screenshots.

    Tons of people have solved this problem. There's at least a dozen solutions out there.

    SerializeReference is also only for non-Unity object types. It's not meant to serialize references to Unity objects.
     
    CodeSmile likes this.
  4. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    7,263
    Thanks for the clarifications!
    Clearly I haven't used any of these often enough and I tend to think that's because there is always an alternative that just plays better with Unity and still works well.