3

In Unity, say you have class Explosion:MonoBehavior, using GetComponent you can trivially

List<Transform> result = new List<Transform>();
foreach (Transform t in here)
    {
    if ( t.GetComponent<Explosion>() )
      result.Add( t );
    }

The list now contains any immediate active or inactive children, which have the "Explosion" component.

I want to make an extension which does that, along the lines

List<Explosion> = transform.Tricky(typeof(Explosion));

So, the extension would look something like ...

public static List<Transform> Tricky(this Transform here, Type ttt)
    {
    List<Transform> result = new List<Transform>();
    foreach (Transform t in here)
        {
        if ( t.GetComponent<ttt>() )
            result.Add( t );
        }
    return result;
    }

However I have utterly failed to figure this out. How to?


Note!

I do know how to do this with generics:

public static List<T> MoreTricky<T>(this Transform here)
  {
  List<T> result = new List<T>();
  foreach (Transform t in here)
      {
      T item = t.GetComponent<T>(); if (item != null) result.Add(item);
      }
  return result;
  }

(so, List<Dog> d = t.MoreTricky<Dog>();) Incredibly, I am so lame I don't know how to do it "normally", passing in the type.

Community
  • 1
  • 1
Fattie
  • 27,874
  • 70
  • 431
  • 719

1 Answers1

2

It is pretty easy, you just need to use the version of GetComponent that takes in a type as one of its parameters and returns a Component object (public Component GetComponent(Type type);), it is the first one listed in the documentation. Be aware that in the documentation the example they show in the section for the non-generic overload is for the generic overload, they do not have a example of the non-generic on the page.

public static List<Transform> Tricky(this Transform here, Type ttt)
{
    List<Transform> result = new List<Transform>();

    foreach (Transform t in here)
    {
        Component item = t.GetComponent(ttt);
        if (item)
            result.Add(t);
    }
    return result;
}

You would call it as like

List<Transform> explosionTransfoms = transform.Tricky(typeof(Explosion))
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431