Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
2
Question by Ardenian · Feb 03, 2017 at 09:20 PM · serializationcustom editorinterfacecustom inspectorinterfaces

What's a good way to handle 'serialization' of interfaces in Unity ?

Since I learned about interfaces, I love using them. However, my dreams crushed when I acknowledged Unity does not support selecting them in the inspector, also known as serialization.

I wondered what would be a good way to add 'something' to make them show up. Obviously, it is somehow related to custom editors and/or property drawers. For some time, I used a workaround with enums and a class with a switch to add the needed Component to my gameObject. This could look like:

 public enum MovementOptions{
     LinearMovement,
     SenodialMovement, 
     CrazyMovement
 } 
 public static Switch{
     public void Movement(GameObject obj, int option){
     switch(option){
         case 0: 
             obj.AddComponent<LinearMovement>();
 // and so on, I guess you get it
 }
 
 public class Person : MonoBehaviour {
     IMovement movement;
     [SerializeField]
     MovementOptions option
     private void Awake(){ movement = Switch.Movement(gameObject, option);}
 }

However, this is very tiresome to use, as you not only have to write that switch class, but also having to call it in Awake. I wondered now whether one could use a workaround with a custom editor. Basically, one would create a dropdown with all class names of classes being inherited from the interface ( maybe using http://wiki.unity3d.com/index.php/Interface_Finder ) and then one would add the necessary component based on the chosen option, declare the interface attribute to the added component and remove the previous chosen one.

How would I code this ? Are there better or popular solutions to this problem ? The aim is to be able to choose a class from a dropdown with all possible options ( classes inherited from the interface), but I am quite unsure on how to actually write this. Using the interface finder I got an array with string names for the dropdown in the custom inspector, but I don't know how to reverse that so I can add the MonoBehaviour class to my gameObject and set the attribute variable for that interface to the added class.

Note: I would prefer not using external tools/plug-ins or whatsoever which will require things like 'BetterMonoBehaviour'.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Scoutas · Feb 03, 2017 at 10:15 PM 0
Share

I think you can add a header [System.Serializable] in front of a class to make it serializable. I've never worker with interfaces, but I wonder if that could work out.

avatar image Ardenian Scoutas · Feb 04, 2017 at 03:29 PM 0
Share

Sadly it ain't that easy. Adding that header to a class inherited from an interface will not show its properties or anything in a $$anonymous$$onoBehaviour which has an attribute of that very interface, as in:

 public interface IValue{
     float $$anonymous$$yValue{get; set;}
 }
 [System.Serializable]
 public Value : IValue{
 [SerializeField]
     private float myValue;
     public float $$anonymous$$yValue[get{return myValue;}set{myValue = value;}}
 }
 public ValueScript : $$anonymous$$onoBehaviour{
 [SerializeField]
 private IValue value;
 }

There won't be a dropdown or something where you could choose a class to use inherited from the interface nor any properties will be shown, thus I wondered whether one could workaround that with using InterfaceFinder and a custom editor.

8 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Jeff-Kesselman · Feb 04, 2017 at 04:42 PM

By definition serialization of an interface makes no sense because serialization is storing the state of the data of an object and Interfaces have no data.

Similarly, "inspecting" an interface makes no sense because the inspector displays the data, which an interface does not have.

If you have sub-classes that share data you should use an abstract parent class. You can use custom inspector inheritance to share inspectors.

http://answers.unity3d.com/questions/51615/do-custom-inspectors-support-inheritance.html

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Ardenian · Feb 04, 2017 at 09:45 PM 0
Share

Thank you for your comment!

I already went through hell when I discovered Unity does not serialize a lot of stuff, I remember using something similar to your abstract class when I desperatly tried to get something to show up in the inspector. I did test it now after your suggestion and to my surprise it went well and seems to work fine. I recall having problems with the serialization of fields in the abstract class not being serialized, 'shown', in the inspector, but now it does.

As for the coding standard, just for interest, is it common practice to write an interface, an abstract base class and then classes inherited from that base class ( outside Unity) ? I've seen so many usage variations of interfaces, $$anonymous$$onoBehaviour and abstract classes as well as class fields inside Unity I have no idea what practice is actually appropriate for coding.

Great thanks for the custom inspector advice, this will prevent me from writing one for each class.

avatar image FortisVenaliter Ardenian · Feb 06, 2017 at 05:13 PM 1
Share

In my experience, use abstract classes for closely related data. For example, Car and Truck could both be subclasses of the abstract Vehicle. Then use interfaces for common functionality, when the data might not necessarily be related. For example, Truck and Crate could both be interfaces of an IStorageContainer interface.

avatar image Ardenian FortisVenaliter · Feb 09, 2017 at 09:45 PM 0
Share

Alright, thank you!

avatar image MikeAtIcejam · Aug 16, 2017 at 09:44 PM 5
Share

I disagree with this answer. Serialization from an interface would act similar to serialization from an abstract base class. The interface knows what object it is and would serialize the child classes data (by child class I mean the class that implemented the interface). I've done this before using json and it works quite well. I don't know how to do this with unity's serialization, but the concept does make sense in general. In fact the children may have no data at all, and just dictate a simple strategy pattern.

avatar image guneyozsan · Jun 01, 2019 at 07:39 PM 1
Share

The problem is Unity injects UI elements (which are not data objects) using its serialization system. If you want to extend Unity's UI elements with your own ones, and separate implementation from types, there is no way to do it in Unity, which is not good. For example I need things like [SerializeField] private IClick deleteButton;, but no way.

avatar image
12

Answer by scarofsky · Jun 20, 2019 at 11:25 AM

Latest News:

Unity 2019.3 will support serialization of reference type, which means you can display List<IFoo> in your inspector, just add a single line above [SerializeReference]. Cool.

For more info, see Unity Forum

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
3

Answer by FortisVenaliter · Feb 04, 2017 at 03:39 PM

Unfortunately, nope. There's no way to natively serialize interfaces. The problem is that when it's serialized to XML, it doesn't store the type within the XML. So, when it goes to deserialize, it won't know which class that implements the interface it should reconstitute.

There are a few ways around this if you get creative, but none are elegant that I know of. The best is simply to store your variable as a component or monobehaviour and cast up. You can write a custom inspector that will reject anything that doesn't implement the interface.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Ardenian · Feb 04, 2017 at 09:50 PM 0
Share

Thank you, that's a great explanation why it does not work! I actually cannot recall seeing one why it does not up to now.

To rephrase your explanation for a beginner like me, the serialization does not work because classes implementing the interface may have different fields and therefore cannot be serialized since the actual type is not stored.

avatar image
1

Answer by Marrt · Feb 12, 2018 at 10:35 PM

Hi man, i just did this workaround and wanted to share it quickly. It just adds another layer of inheritance after "Monobehaviour" since the use case of this is to link monobehaviours that implement the interface. It is the cleanest shortest way i could achieve:

I created a superclass which inherits from monobehaviour and the Interface (can be written into the same .cs in which the interface definition resides in). The abstract superclass implements the interface abstractly. if you create a public variable of that superclass it will create a inspector-slot that accepts any monobehaviour that inherits from it (DamageHandler)

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 namespace ShooterSetup{
 
 [RequireComponent(typeof(Collider))]
 public class DamageReceiver : MonoBehaviour {
     
     [SerializeField] private DamageHandler damageHandler;
     
     public void ApplyHit( int damage ){
         if( damageHandler != null ){ damageHandler.TakeCareOfHit(damage); }
         else{ print("Error, no Handler linked to this Hitbox"); }
     }
 }
 
 /// <summary>Interface for any monobahaviour that might handle damage</summary>
 public interface IDamagable{
     void TakeCareOfHit(int damage);
 }
 
 /// <summary>Interface-implementing superclass for any monobahaviour that might handle damage</summary>
 public abstract class DamageHandler : MonoBehaviour, IDamagable{
     public    IDamagable careTaker;
     public abstract void TakeCareOfHit(int damage); //abstract interface implementation
 }
 
 }


When you have a monobehaviour that needs to be inspector-assignable through the damageHandler variable within DamageReceiver, you just need to inherit from DamageHandler and implement the interface:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using ShooterSetup;
 
 public class EnemyV1 : DamageHandler {
 
     //override for abstract interface implementation
     public    override void TakeCareOfHit( int damage ){
         //Do smth.
     }
 }

Why is it so hard to achieve some format in this post... feel free to edit if you can make it more readable

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image jj_unity328 · Aug 27, 2018 at 03:44 PM 0
Share

But now you can't have a class with multiple interfaces. Unless you define an abstract class for all couple of interfaces you might need together.

avatar image
1

Answer by Peeling · Apr 13 at 03:56 PM

If anyone's still reading this, my solution -

  • Supports classes with multiple interfaces

  • Validates dropped objects and automatically finds components with the appropriate interface

  • Requires only two extra keystrokes per interface access

  • Comes with a bonus autocast to bool so you can easily check if the interface has been assigned a value.

Simply add this template class to your project:

 [System.Serializable]
 public class IRef<T> : ISerializationCallbackReceiver where T : class
 {
     public UnityEngine.Object target;
     public T I { get => target as T; }
     public static implicit operator bool(IRef<T> ir) => ir.target != null;
     void OnValidate()
     {
         if (!(target is T)) 
         {
             if (target is GameObject go)
             {
                 target = null;
                 foreach (Component c in go.GetComponents<Component>())
                 { 
                     if (c is T){
                         target = c;
                         break;
                     }
                 }
             }
         }
     }
 
     void ISerializationCallbackReceiver.OnBeforeSerialize() => this.OnValidate();
     void ISerializationCallbackReceiver.OnAfterDeserialize() { }
 }

To define a serialised interface reference:

 public IRef<MyInterface> thatWasEasy;

and to use it:

 thatWasEasy.I.CallTheFunction();

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

16 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Target field of a MonoBehaviour attribute ? 1 Answer

How can I color a PrefixLabel? 0 Answers

Problems with saving data on GameObject using custom EditorWindow 1 Answer

ScriptableObject not Serializing? 0 Answers

[Solved] Custom editor resets after Play? 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges