Unity开发安卓记事本应用:清除按钮触发NullReferenceException错误求助
Unity安卓记事本Clear按钮空引用错误解决
问题描述
我是Unity完全新手,跟着YouTube上的Jimmy Vegas记事本教程开发安卓应用,制作“Clear”按钮时,点击后控制台报错:
NullReferenceException: Object reference not set to an instance of an object
ButtonControl.ClearText () (at Assets/Scripts/ButtonControl.cs:12)
使用的脚本如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ButtonControl : MonoBehaviour { public GameObject theText; public void ClearText() { theText.GetComponent<InputField>().text = ""; } }
错误原因及解决步骤
这个报错是空引用异常,核心问题是代码里的theText变量未被正确赋值,导致后续调用组件时找不到对象。按以下步骤排查修复:
- 确认场景中存在带有
InputField组件的输入框对象 - 在Unity编辑器的Inspector面板中,找到挂载了
ButtonControl脚本的对象,将输入框对象拖入脚本的theText字段完成赋值 - 检查Clear按钮的OnClick事件绑定,确保已正确关联
ButtonControl对象的ClearText方法,绑定对象不为空
也可以给脚本增加空值判断,避免崩溃同时明确报错原因:
public void ClearText() { if(theText != null) { var inputField = theText.GetComponent<InputField>(); if(inputField != null) { inputField.text = ""; } else { Debug.LogError("theText对象上未挂载InputField组件"); } } else { Debug.LogError("theText变量未赋值,请在Inspector中指定输入框对象"); } }
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

