Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Absolute Reference to Own Prefab

Discussion in 'Prefabs' started by dominikkoller, Jun 12, 2023.

  1. dominikkoller

    dominikkoller

    Joined:
    Jul 26, 2018
    Posts:
    13
    Hello!

    I'd like to have an absolute reference to the own prefab. Here's what I mean by that:

    In a prefab A, there is a MonoBehaviour with a serialized field taking a GameObject. In the Inspector, I assign the prefab A to this field. When the prefab A is instantiated, by default this reference now points to the instance. I want a way for this reference to still point at the prefab.

    Usecase:
    I have a page manager that switches between pages by instantiating them. You open a page by passing a reference of a page prefab. It should be possible for a page to open itself anew - not the current instance, but a new copy of that instance. For that, the instantiated prefab needs a reference to the prefab, not the instance.

    What I tried:
    everything in here: https://forum.unity.com/threads/prefab-with-reference-to-itself.412240/
    None of the suggested solutions there work for me. The one that seems closest is adding a prefab variable to the object. However, I would like my system to work with GameObject rather than my own 'page' type, hence I cannot add a field to store a prefab.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,749
    I think you need to come up from this one level... the way that reference gets reprogrammed to itself is through the Unity instantiation rules and I don't see those changing.

    Instead perhaps you should make a factory that has references to the prefabs on disk and has methods that get called to make items. Anyone, including the item, can say "Make one of these please!" and it's always fresh from a prefab.
     
  3. bloodthirst69

    bloodthirst69

    Joined:
    Oct 1, 2017
    Posts:
    28
    One work around you can do is to "cut the prefab's self referencing link" by going though a scriptableObject or another prefab that isn't a child to the one that you're working with.
    I've already posted a workaround using a scritableObject here.
    In your case it can look like this :

    PR_Page.prefab
    PageCompnent
    - // todo : other fields
    - field : prefabRef PrefabReferenceData <some asset in the project>
    ------- field : gameObject GameObject <reference to PR_Page>

    in this case when you're in the PageComponent and you call "this.prefabRef.gameObject" this result wont point to itself but to the actual prefab asset.
    It's not the most ideal solution , but it works