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’.
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.
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() { }
}
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.
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.
As I’m still on Unity 2017.2 and didn’t find acceptable solution, because my MonoBehaviour has to implement multiple interfaces of such kind. I did next hack:
helper class used for serialization and custom editor handling:
[Serializable]
public class StrategyUnityContainer
{
public IStrategy Strategy
{
get { return _strategyObject as IStrategy; }
set { _strategyObject = value as UnityEngine.Object; }
}
[SerializeField]
private UnityEngine.Object _strategyObject;
}
editor script:
[CustomPropertyDrawer(typeof(StrategyUnityContainer), true)]
public class StrategyUnityContainerPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
label = EditorGUI.BeginProperty(position, label, property);
var strategyHolder = property.serializedObject.targetObject;
var fieldInfo = strategyHolder.GetType().GetField(property.propertyPath, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var strategyProxy = fieldInfo.GetValue(strategyHolder) as StrategyUnityContainer;
if (strategyProxy == null)
{
strategyProxy = new StrategyUnityContainer();
fieldInfo.SetValue(strategyHolder, strategyProxy);
}
EditorGUI.BeginChangeCheck();
strategyProxy.Strategy = EditorGUI.ObjectField(position, label, strategyProxy.Strategy as Object, typeof(IStrategy), true) as IStrategy;
if (EditorGUI.EndChangeCheck())
{
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
property.serializedObject.ApplyModifiedProperties();
}
EditorGUI.EndProperty();
}
}
Hope this will help somebody
PS: you can fill field within editor only by drag&drop, asset selector dialog won’t show any objects which implements interface for some reason
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
way too late answer, but i used a supertype, monobehavior or scripatable object for example, then try to cast to check if the object implements the interface.
the only caveat is that you must know the class implements the interface in development, but at least at runtime it will work.
in my case it was a scripatable object so i did
public class LoadSettings : MonoBehaviour
{
[SerializeField]
public ScriptableObject[] list;
public bool onStart;
// Start is called before the first frame update
void Start()
{
if (onStart)
Load();
}
public void Load()
{
foreach (var obj in list)
{
if (obj is ILoadHandler handler)
{
handler.Load();
Debug.Log("load");
}
}
}
public void Save()
{
foreach (var obj in list)
{
if (obj is ILoadHandler handler)
{
handler.Save();
Debug.Log("save");
}
}
}
}