GetComponentInParent doesn't behave like I'd expect

The documentation for Component.GetComponentInParent states:

When called on an instantiated object, this behaves as written: it will return the requested component whether that component exists on the target object itself OR in any of the target object’s parents.

When called on a non-instantiated prefab, this function DOES NOT WORK. It appears to return null always, regardless of the layout of the prefab. It doesn’t matter whether the target component is at the prefab root or in one of its children, nor does it matter whether I call GetComponentInParent on the prefab root or on one of its children, or any combination thereof.

If I simply call regular ol’ GetComponent on the prefab, the component is returned correctly. I can also use this to manually walk up the prefab hierarchy and find components like you’d expect. So I can set up a prefab that looks like this:

Root
    Child 1
        Child 2

Then I can write some code like this:

for(Transform t = testPrefab.transform; t != null; t = t.parent)
{
    T test = t.GetComponent<T>();
    if(test != null)
        return test;
}

And I can call that code on Child 2 of that non-instantiated prefab, and it’ll correctly find the desired component whether it’s on Child 2, Child 1, or Root.

It’d be really sweet if GetComponentInParent would work in a consistent/expected way when used on prefabs, especially since there doesn’t appear to be anything functionally preventing this. :expressionless:

2 Likes

I can verify this on my side, using the naive implementation (or in my case, NGUI’s implementation) works as expected.

Passing includeInactive=true to GetComponentsInParent should do the trick. The same is true for GetComponentsInChildren.

Shouldn’t that be considered a bug and reported as such?

1 Like

And GetComponentsInChildren work on Prefab just fine without “includeInactive = true”. I think this should be fixed.

second this.

This is still an issue in 2019.4.8 (not critical enough for me to spend my time submitting a bug report though).

I randomly stumbled upon this thread and wanted to let you know that I reported this in June 2020 :slight_smile:

3 Likes

Same issue in 2022.3.11. Seems like very unexpected behaviour to me that it behaves different in prefabs compared to GetComponentInChildren().

It seems that adding IncludeInActive = true solves it. But then it retrieves inactive results, when I only want active game object returned (as should be the case by default I think)