Search Unity

Bug Prefab spontaneously loses serialized references

Discussion in 'Scripting' started by WARdd, Jan 14, 2023.

  1. WARdd

    WARdd

    Joined:
    Aug 10, 2015
    Posts:
    29
    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.

    PrefabProblem.png

    Relevant code:
    Code (CSharp):
    1.  
    2. //HUD.cs
    3. ...
    4.     public BotInfoTag botTagPrefab;
    5.     public Transform botTagPanel;
    6. ...
    7.     public void AddBotTag() {
    8.         Instantiate(botTagPrefab, botTagPanel).Init();
    9.     }
    10. ...
    11.  
    12.  
    13.  
    14. //BotInfoTag.cs
    15. using UnityEngine;
    16.  
    17. /// <summary>
    18. /// Tag in UI layer that is used to display info about a given bot.
    19. /// </summary>
    20. public class BotInfoTag : MonoBehaviour {
    21.  
    22.     [SerializeField]
    23.     private TMPro.TMP_Text playerNameText;
    24.     [SerializeField]
    25.     private CanvasGroup cg;
    26.  
    27.     public void Init() {
    28.  
    29.         //Ugly fix I would prefer to avoid
    30.         /*
    31.         if(cg == null)
    32.             cg = GetComponent<CanvasGroup>();
    33.         if (playerNameText == null)
    34.             playerNameText = GetComponentInChildren<TMPro.TMP_Text>();
    35.         */
    36.        
    37.         cg.interactable = false; //null reference here, cg is otherwise never referenced
    38.         cg.blocksRaycasts = false;
    39.         playerNameText.text = "Cool player dude";
    40.     }
    41. }
    42.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    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.
     
  3. WARdd

    WARdd

    Joined:
    Aug 10, 2015
    Posts:
    29
    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.
     
    Kurt-Dekker likes this.