List of all components as their end type

So I’m trying to do a Mary Sue for Undo.RecordObject function… basically, something that records recursively all the behaviours in a game object (please don’t ask why).

I tried doing this:

        Behaviour[] allBehaviours = transform.GetComponentsInChildren<Behaviour>();

        foreach (Behaviour behaviour in allBehaviours) {
            Undo.RecordObject(behaviour, "mary sue");
        }

But it won’t work, because the Undo is recording the behaviour as Behaviour, ignoring all his properties as implementation.

What can I do? :frowning:

Idk, maybe passing it as serialized object instance or it’s properties individually will work?

As a quick fix you can use “is” checks like that :

    void SomeFunction ()
    {
        foreach (Behaviour b in allBehaviours)
        {
            if (b is TypeA)
                SomeCode();
            else if (b is TypeB)
                SomeCode();
            else if (b is TypeC)
                SomeCode();
        }
    }

Not sure this is what you are looking for, I don’t think this kind of code is good practice, but this could be a solution.

that would work, but I’d have to make one if for every class that inherits from Behaviour… it would be a very long list n.n’

Maybe an interface or attribute will help?
With interface, your can just

foreach (IMyContract b in allBehaviours)
{
    b.SomeMethod();
}

with attributes it’s a little harder, but attributes allows you not to move code from editor class to beahviours and this make things easier with builds and such

public CustomProcessingAttribute : Attribute {
}

[CustomProcessing(Processing.DoWhatever)]
class SomeBehaviour : MonoBehaviour
{
}

foreach (Behaviour b in allBehaviours)
{
   var attribute = b.GetType().GetAttribute<CustomProcessingAttribute>();
   attribute.Process();
  // or
  switch(attribute.ProcessingType)
{
case 1:
dosomth(b);
break;
}
}

If you’d like to adopt the attribute solution, read this https://www.infoworld.com/article/3006630/how-to-work-with-attributes-in-c.html
My pseudocode won’t even compile, it’s here just to show the concept.