首页 > 解决方案 > 如何将 List.count 分配给变量?

问题描述

我试图总结 C# Unity 中两个列表的长度,但没有成功。整数变量“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);

    }

标签: c#unity3d

解决方案


调用会在调用.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 

在您的示例中,您似乎不需要oneCountandtwoCount变量:

void Final()
{
   Debug.Log(oneList.Count + twoList.Count);
}

推荐阅读