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.
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";
}
}
