GetComponentInChildren gets wrong inheritance

Im using GetComponentInChildren to get one component of a child object.

The problem is that i have another Game object with a script that inheritate form the class im trying to get.

if i call GetComponentInChildren() i get ClassB.

Is there any way to disable GetComponentInChildren to find inheritate classes?

no

but you can write your own that finds a direct match.

See the GetComponentInChildren function just tests if the type ‘is’ some other type. And well ClassB is a ClassA.

If you know the child it is on, you can just access the child first and then grab the component from it.

OR

You can write your own function to loop over all the children and find the component on your own terms. You’re going to test if the Type of the component is the exact same type that you’re looking for:

if( comp.GetType() == tpLookingFor ) return comp;

the annoying part is choosing how you want to loop over the children. A depth first loop is a little weird to write… (GetComponentInChildren does a depth first loop)

here’s a quick thrown together example… (untested, written in notepad)

function GetComponentInChildrenExplicit(parent : Transform, tp : Type) : Component
{
    var stack : Array = new Array();
    stack.push(new Array(parent, 0));
    while (stack.length != 0)
    {
        var arr : Array = stack.pop();
		for(var comp : Component in arr[0].GetComponents(tp))
		{
			if(comp.GetType() == tp) return comp;
		}
        arr[1]++;
        for(var child : Transform in arr[0])
		{
            stack.push(new Array(child, parent[1]));
		}
    }
}

Thanks a lot :slight_smile:
I have gone the "easy " way and wired everything up in the inspector.

The (untested, but) cool way of doing things:

using System.Linq;

var wantedComponent = GetComponentsInChildren<ClassA>().FirstOrDefault(x => x.GetType() == typeof(ClassA));

FirstOrDefault is probably not working with unity , because its DotNet 3.5 plus required and unity uses only Mono (DotNet 2.0) (untestet)