正在从购物系统获取null引用



对于Context,我对Unity很陌生,所以我遵循了一个教程。以下是链接:https://www.youtube.com/watch?v=Oie-G5xuQNA

为了更容易访问代码,我也会在这里发布:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonInfo : MonoBehaviour
{
public int ItemID;
public Text PriceText;
public Text QuantityText;
public GameObject ShopManager;
// Update is called once per frame
void Update()
{
PriceText.text = "Price: $" + ShopManager.GetComponent<ShopManagerScript>().shopItems[2, ItemID].ToString();
QuantityText.text = ShopManager.GetComponent<ShopManagerScript>().shopItems[3, ItemID].ToString();
}
}

这里还有第二个脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ShopManagerScript : MonoBehaviour
{
public int [,] shopItems = new int[5,5];
public float coins;
public Text CoinsText;

void Start()
{
CoinsText.text = "Coins" + coins.ToString();
// ID's
shopItems[1, 1] = 1;
shopItems[1, 2] = 2;
shopItems[1, 3] = 3;
shopItems[1, 4] = 4;
// Price
shopItems[2, 1] = 10;
shopItems[2, 2] = 20;
shopItems[2, 3] = 30;
shopItems[2, 4] = 40;
// Quantity
shopItems[3, 1] = 1;
shopItems[3, 2] = 1;
shopItems[3, 3] = 1;
shopItems[3, 4] = 1;

}
public void Buy()
{
GameObject ButtonRef = GameObject.FindGameObjectWithTag("Event").AddComponent<EventSystem>().currentSelectedGameObject;
if(coins >= shopItems[2, ButtonRef.GetComponent<ButtonInfo>().ItemID])
{
coins -= shopItems[2, ButtonRef.GetComponent<ButtonInfo>().ItemID];
shopItems[3, ButtonRef.GetComponent<ButtonInfo>().ItemID]++;
CoinsText.text = "Coins" + coins.ToString();
ButtonRef.GetComponent<ButtonInfo>().QuantityText.text = shopItems[3, ButtonRef.GetComponent<ButtonInfo>().ItemID].ToString();
}
}
}

最后一件事:这是错误消息本身:

NullReferenceException:对象引用未设置为对象的实例ShopManagerScript.Buy(((位于Assets/Scripps/UI/Shop System/ShopManagerScript.cs:43(

在Buy((方法中,您似乎正在调用AddComponent将EventSystem添加到标记为"的对象中;事件";。很可能这个对象已经有一个EventSystem,所以它无法添加另一个,并且它提供了对ButtonRef对象的null引用。您很可能希望在那里调用GetComponent来获得已经存在的EventSystem组件

相关内容

  • 没有找到相关文章

最新更新