Prefab spontaneously loses serialized references

I'm instantiating a prefab that has a few serialize fields that reference components within the same prefab. Without interacting with those fields in any way, they suddenly become null leading to a UnassignedReferenceException. Indeed in the inspector, the references dissapear, even though the prefab still contains the relevant components.

8730171--1181238--PrefabProblem.png

Relevant code:

//HUD.cs
...
    public BotInfoTag botTagPrefab;
    public Transform botTagPanel;
...
    public void AddBotTag() {
        Instantiate(botTagPrefab, botTagPanel).Init();
    }
...



//BotInfoTag.cs
using UnityEngine;

/// <summary>
/// Tag in UI layer that is used to display info about a given bot.
/// </summary>
public class BotInfoTag : MonoBehaviour {

    [SerializeField]
    private TMPro.TMP_Text playerNameText;
    [SerializeField]
    private CanvasGroup cg;

    public void Init() {

        //Ugly fix I would prefer to avoid
        /*
        if(cg == null)
            cg = GetComponent<CanvasGroup>();
        if (playerNameText == null)
            playerNameText = GetComponentInChildren<TMPro.TMP_Text>();
        */

        cg.interactable = false; //null reference here, cg is otherwise never referenced
        cg.blocksRaycasts = false;
        playerNameText.text = "Cool player dude";
    }
}

Prefabs can never refer to something in a scene, only the other way around. Is this your problem?

The reason: prefabs are files on disk, the scene is ephemeral and only in memory.

A bit awkward replying so quickly, but after trying literally everything else, just reimporting the prefab magically fixed it.
Clicking on the prefab in the inspector would show the 2 fields as empty, while opening it showed the fields filled in.

1 Like