Unity生成含图片与TMPro文本列表时触发空引用异常
Unity恒星系统列表生成问题排查与修复
问题概述
- 绑定Inspector数据后触发
NullReferenceException(LocationManager.cs第37行) - 配置4个列表项但仅生成2个,所有详情文本不显示
- 模板对象
Destroy调用在编辑器中不生效 - 怀疑TextMeshPro(TMP)兼容性问题
一、LocationManager脚本修复
1. 空引用异常根源
第37行尝试获取旧版Text组件,但UI实际使用的是TMP组件,无法匹配导致空引用。
2. 代码修正
将循环内所有GetComponent<Text>()替换为GetComponent<TextMeshProUGUI>():
void Start() { GameObject MapSelectorTemplate = transform.GetChild(0).gameObject; GameObject g; int N = allLocations.Length; for (int i = 0; i < N; i++) { g = Instantiate(MapSelectorTemplate, transform); g.transform.GetChild(0).GetComponent<Image>().sprite = allLocations[i].LocationImage; // 替换为TMP组件获取 g.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = allLocations[i].SystemName; g.transform.GetChild(2).GetComponent<TextMeshProUGUI>().text = allLocations[i].LocationName; g.transform.GetChild(3).GetComponent<TextMeshProUGUI>().text = allLocations[i].DockType; g.transform.GetChild(4).GetComponent<TextMeshProUGUI>().text = allLocations[i].IndustryType; g.transform.GetChild(5).GetComponent<TextMeshProUGUI>().text = allLocations[i].SystemName; } Destroy(MapSelectorTemplate); }
3. 生成数量异常排查
- 检查Inspector中
allLocations数组的元素数量,确保已添加4个完整项 - 确认模板对象的子物体索引完全匹配代码中的调用,若某一子物体缺失,会触发异常中断循环,导致生成数量不足
二、Demo脚本核心错误修复
1. 变量赋值逻辑错误
原代码错误地将组件对象赋值给文本属性,修正为组件引用赋值:
void Start () { // 修正组件赋值逻辑 textmeshPro = GetComponent<TextMeshProUGUI>(); GameObject buttonTemplate = transform.GetChild(0).gameObject; GameObject g; int N = allGames.Length; for (int i = 0; i < N; i++) { g = Instantiate(buttonTemplate, transform); g.transform.GetChild(0).GetComponent<Image>().sprite = allGames[i].gameIcon; g.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = allGames[i].gameName; g.transform.GetChild(2).GetComponent<TextMeshProUGUI>().text = allGames[i].gameDescription; } Destroy(buttonTemplate); }
2. 结构体数据类型错误
Game结构体不应存储TMP组件引用,需改为存储字符串文本:
[Serializable] public struct Game { // 替换为string类型存储文本内容 public string gameName; public string gameDescription; public Sprite gameIcon; }
三、模板对象销毁问题
- 运行时
Destroy(MapSelectorTemplate)会正常销毁对象,但编辑器编辑模式下不生效 - 若需在编辑模式销毁,改用
DestroyImmediate(MapSelectorTemplate);正式逻辑中推荐运行时销毁,编辑模式下可手动禁用模板对象(SetActive(false))替代销毁
内容的提问来源于stack exchange,提问作者Lexicon11
相关产品推荐
相关产品推荐

