An object having a pointer to its own prefab ?

Sometimes, when I have an object which is an instance of a prefab, I want to have a reference to said prefab. As far as I know, there is no “GetPrefab” function (am I wrong?), so the “obvious” solution is to give the object a pointer to its own prefab (A):

Only problem is that it doesn’t work. The reason is that when a prefab having a pointer to itself is instanciated, the pointer becomes a pointer to the instance, not to the prefab (B).

(On a sidenote, I stumbled upon this problem in a situation where enemy NPCs had each a pointer to a “successor prefab” which was instanciated when the NPC was killed - worked fine except when the successor was based upon the same prefab, and the symptom were NPCs created with 0 life points. It took me a while to figure out what was the actual problem.)

So far, the only solution I found is to pass by another “proxy” prefab (which is never instanciated) : The prefab (and thus it’s instances) have a pointer to the proxy prefab, which has a pointer to the prefab (C). However, this is a rather ugly makeshift solution.

Hence my question : Does anyone of you know a more elegant solution ? Or maybe a “GetPrefab” function which makes the prefab pointer obsolete ?

You could instantiate the object, then make use of the SendMessage method. Send a message to it from the instantiating object containing the prefab pointer. Then just store it in the instantiated object. Not elegant, but simple

The workaround I’ve always used for this is to have two identical prefabs and have each reference the other.

It’s obviously not ideal though because you have to keep the two prefabs in sync. I’m sure there are other ways you could solve the problem as well (for example, store the prefab itself in a publicly accessible static variable, and have the the object grab a reference to it in Awake()).

I did not know that this was the behaviour.

Question:

  • Why do you need a pointer to the Prefab of an instanciated object?
  • Try using a static Property - and set the default instance in the “Project View”

The case where this usually comes up is ‘recursive instantiation’, where an object is intended to spawn new objects of the same kind.

Jesse:

Would a factor implementation work for this case?

instead of letting the object handle the spawning, just pass the object to the factory.
Which will then based on the object type, spawn the necessary prefab?

Thanks

Sure, there’s all kinds of ways it could be done. It’s just that the usual method for instantiating new objects is for the script doing the instantiating to store a reference to the prefab from which the new objects should be cloned, which ends up not working correctly in this particular case.