Unity错误。通过按钮单击方法将实例添加到静态列表时,为NullReferenceExeption

问题描述 投票:0回答:1

所以基本上。我当时在游戏中从事模型制作,完成后我想对其进行测试。你猜怎么了。它没有用,我的老师说,他没有看到任何错误。此问题涉及3个类。第一类-没什么困难(我要添加到列表中的实例):

public class MaterialIngot
{
    public MaterialIngot(string material,string type, string path, int id, int price, bool melted)
    {
        Material = material;
        Type = type;
        Path = path;
        ID = id;
        Price = price;
        Melted = melted;
    }
    public string Material { get; set; }
    public string Type { get; set; }
    public string Path { get; set; }
    public int ID { get; set; }
    public int Price { get; set; }
    public bool Melted { get; set; }

}

2nd class-具有静态字段的静态类。为了简单起见,我只添加解决此问题所需的代码。

public static class ShopTempData
{
    public static List<MaterialIngot> tempMaterialIngots { get; set; }

}

3rd class-Monobehaviour类,附加到按钮上。

public class ShopHandler : MonoBehaviour
{
    [Header("Input")]
    public string Material;
    public string Type;
    public int Price;
    private string Name;
    private int AllCost;

    public void AddItem()
    {
        Name = Material + Type;

        switch (Type)
        {
            case "Ingot":
                //Debug.Log(Paths.ingotPaths[Name]); //this works
                var x = new MaterialIngot(GetComponent<ShopHandler>().Material, GetComponent<ShopHandler>().Type, Paths.ingotPaths[Name], Pdata.ID + 1, GetComponent<ShopHandler>().Price, false);

                Debug.Log(x.ID);
                Debug.Log(x.Material);
                Debug.Log(x.Type);
                Debug.Log(x.Path);
                Debug.Log(x.Price);
                Debug.Log(x.Melted);

                ShopTempData.tempMaterialIngots.Add(x); //ERROR IS HERE - Unity says that..

                Pdata.ID += 1;

                Debug.Log("Added");
                Debug.Log(ShopTempData.tempMaterialIngots);
                break;
        }
        //Aktualizace ceny
        AllCost += Price;

    }
}

如您所见,它并不那么复杂。我只是调用该函数,创建一个实例,在其中包含数据(Debug.Log()正确打印数据),然后尝试将该实例添加到静态列表中。

此显示每次(图片):ERROR MESSAGE

如果您有任何想法,怎么了。任何建议将不胜感激。

c# unity3d static onclick nullreferenceexception
1个回答
0
投票

看起来好像没有初始化列表,您刚刚声明了一个类型为List<MaterialIngot>和名称为tempMaterialIngots的属性,但实际上并没有创建List<MaterialIngot>对象,因此为空引用。 >

尝试一下:

public static class ShopTempData
{
    public static List<MaterialIngot> tempMaterialIngots { get; set; } = new List<MaterialIngot>();            
}

而且,如果您只打算有一个列表,即初始化后不会创建新的List<MaterialIngot>对象,我会将其实现为字段,而不是属性:

public static class ShopTempData
{
    public static List<MaterialIngot> tempMaterialIngots = new List<MaterialIngot>();            
}
© www.soinside.com 2019 - 2024. All rights reserved.