gpt4 book ai didi

C# 列表属性

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:18 25 4
gpt4 key购买 nike

我有一个已设置为属性的列表。我想从另一个类添加到这个列表但是当我运行我的代码时告诉我我有空引用。但是,我可以很好地从列表中读取内容。只有当我添加到列表时才会显示错误。

我做错了什么?

属性类

public List<string> ownedShips;

void Start()
{
ownedShips = new List<string> ();

}

public List<string> Ships
{
get {return ownedShips;}
set {ownedShips = value;}
}

从另一个类添加到列表:

    public int shipCost; 
public bool purchasedShip;
public string shipName = "test";
TESTPlayerAccount player;


// Use this for initialization
void Start ()
{
player = new TESTPlayerAccount ();
Debug.Log (player.Currency);
}


public void BuyShip()
{
if(player.Currency >= shipCost)
{
player.Ships.Add(shipName);

}


}

最佳答案

我想你需要这样的东西

class TESTPlayerAccount 
{
private List<string> ownedShips;

public TESTPlayerAccount ()
{
ownedShips = new List<string>();
}

public List<string> Ships
{
get {return ownedShips;}
}
}

关于C# 列表属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31571571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com