I'm attempting to summate the lengths of two lists in C# Unity, but have been unsuccessful. The integer variables "oneCount" and "twoCount" return 0 every time, even after increasing the list size. I'm sure there's an easy solution, but I'm completely stuck.
My code looks like the following:
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);
}
Calling .Count
gives you the value at the time of that call.
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
It seems that in your example you don't need the oneCount
and twoCount
variables:
void Final()
{
Debug.Log(oneList.Count + twoList.Count);
}
Modify you finall method as below it will work
void Final()
{
Start(); // since assignment you have done in this method
Debug.Log(oneCount + twoCount);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.