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'.
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.
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.
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
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.
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.
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.
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.
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
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.
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.
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
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.
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();
Your answer
Follow this Question
Related Questions
Target field of a MonoBehaviour attribute ? 1 Answer
What is the real purpose of ISerializationCallbackReceiver interface? 1 Answer
Serialize child ScriptableObject asset values in parent ScriptableObject asset. 0 Answers
Custom inspector ReorderableList gives an error when adding item to list 0 Answers
How can I color a PrefixLabel? 0 Answers