problem with interface and abstract class in unity

Hello,
There is a problem I always face. If I use interface I cannot use drag/drop in editor. Also, FindObjectsOfType doesn’t work because it is not an object. There is the same problem when I use abstract class. Is there any solution?

Of course you can’t use an interface in this case since Unity can only serialize references of types which are derived from UnityEngine.Object. However an abstract class which is derived from MonoBehaviour works just fine. I just created an example in my test project just like yours and it works just fine. I created 3 files TryClass, TryClass1 and Manager

// TryClass.cs
public abstract class TryClass : MonoBehaviour
{
    public abstract void MyMethod();
}

// TryClass1.cs
public class TryClass1 : TryClass
{
    public override void MyMethod()
    {
        Debug.Log("TryClass1");
    }
}

// Manager.cs
public class Manager : MonoBehaviour
{
    public TryClass[] list;
    
    void Start()
    {
        foreach (var c in list)
            c.MyMethod();
    }
}

First option, class should inhered from MonoBehavior (or Component, not sure about this).

Second option, class (or struct) should be serializable.

This is a topic I touched on in my SOLID design training course.
FindObjectOfType doesn’t work with interfaces, though GetComponent does.

So, here’s something you can do is :

  1. find all root objects, using System.Linq to filter all transform with no parent

    List rootTransforms = (from t in FindObjectsOfType()
    where t.parent == null
    select t).ToList();

  2. then use GetComponentsInChildren<Interface>() on them.

    List _specialEventHandlers = new List();

    foreach (Transform t in rootTransforms)

     _specialEventHandlers.AddRange (t.GetComponentsInChildren<ISpecialEventHandler>());