Unity 2D中按钮点击调用GameObject脚本函数的报错排查
Unity 2D按钮点击监听器空引用问题解决
我在Unity 2D场景中有一个名为WoodCutter(Clone)的GameObject,挂载了WoodHarvester.cs脚本。场景内有UI Canvas,我通过代码在Canvas中实例化新按钮,想给按钮添加点击监听器,点击后调用该GameObject上脚本的指定函数(场景中可能存在多个相同的GameObject)。
当前代码步骤
- 声明GameObject变量:
public GameObject thisBuilding; - 将当前GameObject赋值给该变量:
thisBuilding = this.gameObject; - 在UI Canvas中创建按钮:
Transform btnTransform = Instantiate(btnTemplate, transform); btnTransform.SetParent(btnParent, true); btnTransform.gameObject.SetActive(true); btnTransform.GetComponent<RectTransform>().anchoredPosition = new Vector2(xPosition, yPosition); btnTransform.GetComponentInChildren<TextMeshProUGUI>().text = "Grow";
上述步骤均正常,但添加点击监听器时出现错误:
出错的监听器代码
btnTransform.GetComponent<Button>().onClick.AddListener(() => { thisBuilding.GetComponent<WoodHarvester>().GrowButton(); });
报错信息
NullReferenceException: Object reference not set to an instance of an object
GrowButton函数定义
public void GrowButton() { Debug.Log("Growth!"); }
问题解决
原因是直接通过GetComponent<Button>()获取组件为空,修改为通过Find方法定位按钮组件:
Button thisButton = btnTransform.Find("button").GetComponent<Button>();
内容的提问来源于stack exchange,提问作者Paul Sotena
相关产品推荐
相关产品推荐

