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. ![]()