unity prefab youofofofyou

unity prefab youofofofyou

The answer is actually pretty simple: You don’t

Unity does not have any relation between the source object and a clone of that object. You can instantiate any kind of object at runtime and cloning a prefab or cloning an instance makes no difference at all. The concept of prefab instances is an editor feature.

Though if you need some kind of relationship at runtime you can of course always set that up yourself. As you probably know a prefab can not have a reference to itself because when instantiating that prefab, all inner references get “fixed” to the newly created instance. So the reference to the prefab would essentially be lost. Though you can simply re-set such a variable right after you instantiate a prefab. So the general approach is that you have some kind of monobehaviour on your prefab that has a variable that stores the prefab reference. Whenever you instantiate a class you would actually revert the “fix” after it has been instantiated.

var inst = Instantiate(prefab);
inst.GetComponent().prefab = prefab;

This way the prefab variable in the PrefabInst script on the prefab would actually contain a reference to the original prefab.

文章来源:https://discussions.unity.com/t/how-to-determine-the-prefab-of-an-instance-in-runtime-how-to-determine-the-main-prefab-of-an-instance/252530