Need to make a reference in a prefab to itself not to the created instance

Hello,

Let’s say that we have a prefab X and it has a script that has a reference called “prefab” to the prefab X, in other words it points to itself. I created the GameObject, attached my script on it, created a prefab, dragged the GameObject to it then selected the prefab and then dragged it to the reference “prefab” in the script.

My problem is when I drag the prefab into the scene the reference “prefab” refers to the created instance not the prefab X itself.

I understand that by doing the steps I did Unity thought that I want a reference in a GameObject referring to itself not to the actual prefab.

I tried the following to prevent instances of the prefab to set the value of “prefab” but it didn’t work:

GameObject prefab;
    public GameObject Prefab
    {
        set
        {
            PrefabType objectType = PrefabUtility.GetPrefabType(gameObject);
            if (objectType == PrefabType.Prefab)
                prefab= value;
        }
        get
        {
            return prefab;
        }
    }

When I did that “prefab” became null, I thought that it will keep its value when it was still a prefab but apparently when an instance is created from prefab it’s a new created GameObject with the same components then its values are copied from the prefab.

Any solution for that doesn’t use Resources.Load()?

An alternate method to having a manager script is to have a scriptable object make the connection like so:

public class PrefabConnection : ScriptableObject {
    		
    		#region PUBLIC_VARIABLES
    
    		[SerializeField] private GameObject prefab;
    
    		#endregion // PUBLIC_VARIABLES
    		
    		#region PUBLIC_METHODS
    
    		public GameObject GetPrefab() {
    			return prefab;
    		}
    		
    		#endregion // PUBLIC_METHODS
    	}

Then the object can use this scriptable object as the reference to its own prefab, the downside is that you have to have a scriptable object per prefab, but in my case no object will reference the newly created one so this works great. You could also create a single scriptable object that references all prefabs to make less data files in the project.

You have to have a manager (which could be an instantiator or a human or maybe a custom editor) assign the prefab reference. An object can’t know what prefab it came from without help.

Thing thing = (Thing)Instantiate(prefab);
thing.prefabSource = prefab;

You might be able to [ExecuteInEditMode] something on Start that searches the project for a prefab that looks close enough to “this” and then assign that as the prefab.