How do you reference an object's underlying prefab?

Can’t seem to find an answer on this.

I want to pass a reference to an object’s underlying prefab. It’s an inventory system, so when you pick up one instance, I want to refer to the prefab, rather than the gameObject at hand. Is there a way to do this?

If I get you right, you can use Resources.Load (https://docs.unity3d.com/ScriptReference/Resources.Load.html)

I’m not sure I understand what you want to do, but if I guess right:
You don’t really need to do that. In run-time there are no prefabs really. You can use any game objects to instantiate a new one.

What do you exactly want to do? (Your explanation is about technicality, not goal to achieve)

I came up with a workaround, but here’s what I was trying to do:

I wanted to be able to pick up an item in the world, like a key, and delete it. The player’s inventory would store a reference to the prefab, not the object, and then when you tried to use the object, it would instantiate an instance of the prefab.

I just added a reference in the object and passed that to the player, so I guess that works.

I’m not sure you’re saying the same thing already, but when I instantiate the object I give the instantiated object a reference to the original prefab. Something like this:

public class SomeClass : MonoBehaviour
{
    [HideInInspector]
    public GameObject MyOriginalPrefab = null;
}
GameObject newInstance = Instantiate(Prefab);
newInstance.GetComponent<SomeClass>().MyOriginalPrefab = Prefab;

If you instead try to have a reference built into the original prefab to itself, that reference will end up pointing to the instance of the prefab in the scene, and not the prefab in the Assets folder after you instantiate it.

2 Likes

Yeah, that’s what I ended up doing. I thought there might be a better or more efficient way of referring to the prefab, but a solution that works is better than a theory that doesn’t!

1 Like

Maybe PrefabUtility.GetPrefabAssetType could be usefull?