[英]How to assign List.count to a variable?
我試圖總結 C# Unity 中兩個列表的長度,但沒有成功。 integer 變量“oneCount”和“twoCount”每次都返回 0,即使在增加列表大小之后也是如此。 我確信有一個簡單的解決方案,但我完全被卡住了。
我的代碼如下所示:
public class list : MonoBehaviour
{
List<int> oneList = new List<int>();
List<int> twoList = new List<int>();
int oneCount;
int twoCount;
void Start()
{
oneCount = oneList.Count;
twoCount = twoList.Count;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
oneList.Add(1);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
twoList.Add(1);
}
if (Input.GetKeyDown(KeyCode.G))
{
Final();
}
void Final()
{
Debug.Log(oneCount + twoCount);
}
調用.Count
會在調用時為您提供值。
var list = new List<int>();
var c1 = list.Count; // c1 is 0
list.Add(1);
var c2 = list.Count; // c2 = 1, and c1 is still 0
在您的示例中,您似乎不需要oneCount
和twoCount
變量:
void Final()
{
Debug.Log(oneList.Count + twoList.Count);
}
修改你的finall方法如下它會起作用
void Final()
{
Start(); // since assignment you have done in this method
Debug.Log(oneCount + twoCount);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.