Unity on GetComponentsInChildren uses extension methods to avoid getting parent objects

1: I believe everyone uses the GetComponentsInChildren method? But when using this method again,

       If GetComponentsInChildre<T>(),

    If the parent object and the child object both have the same T, then the resulting array will also contain the T in the parent object . This is not necessary in many cases.

    So how to solve this problem?


2: Solution

I believe you will be able to write it, here I am writing an extension method (specific C# extension method, find Du Niang)

1: First create a MyExtension class, do not inherit mono (note static), and then write a method

Then use

That’s fine, but GetComponentsInChildren has an overloaded method, I’ll mention it here
        public T[] GetComponentsInChildren<T>(bool includeInactive);
    This overload, the default is false, includeInactive=true, then you can still get it if the T object is closed when you get the child object.
If includeInactive=false, then no closed T object will be obtained    

 

      

When true

Let's modify the extension method we wrote (in fact, there is nothing to modify QAQ)

Then just use it as before

ok! ! !

Guess you like

Origin blog.csdn.net/K20132014/article/details/71761655