How to get prefab asset Object of a Nested Prefab Variant?

I find PrefabUtility to be quite a confusing API, but understand that nested prefabs and prefab variants have made it so. However i can’t seem to find a single method in PrefabUtility that gets me what i want here.

I have a prefab (let’s call it A) that contains a nested prefab, this nested prefab is itself a prefab variant (let’s call it BVariant).

So we have A, we have B and BVariant.

What i want to get is the BVariant asset from the BVariant nested prefab instance in A.

GetCorrespondingObjectFromSource returns BVariant (object in prefab A) as stated in the docs.

GetCorrespondingObjectFromOriginalSource gets me prefab asset B, not BVariant.

The only way i have found to get what i want so far is to call GetCorrespondingObjectFromSource twice if the prefab is not the IsOutermostPrefabInstanceRoot, which just doesn’t seem right.

Is there a suggested way of doing this? Or am i missing something?

Unity version: 2021.3.16

Thanks.

Hi! You can get asset’s path by PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot and load it any way you like.
This will work for your needs! Checked the cases when prefab variant instance is nested and not (result will be BVariant asset).

2 Likes

Thank you for your response! I was meaning to follow up that we discovered this in the end.

The strange thing is that if you look at what this does, it calls a method GetOriginalSourceOrVariantRoot which is exactly what we want, but is not exposed to us, it is internal only.

I wonder why that is, maybe Unity will expose it in a future version.

But yes you are right, using GetPrefabAssetPathOfNearestInstanceRoot and then loading the asset manually gets me what i needed. Thank you.

1 Like

It’s hard to look at method you can’t call…
Thank you too cause I was searching for a method that will return original prefab from prefab variant instance :stuck_out_tongue: