-2

I'm new to lists and arrays, so I'm not sure what's happening here. I understand the concepts of arrays/lists in general, but I'm trying to add new values upon a key press. The problem is that it seems to be adding it to the list, but when I'm using "myValue.Count >= someNumber" it doesn't return the max value even though it's well over it. If I were to use a for loop however, it works but I'm trying to add it by increments of one and not in once instance. I tried searching this(as well as MSDN) but I couldn't find a solution. Any help would be appreciated. Edit: For those familiar with Unity, it's being called in the "Update" method.

 void Numbers()
{

    var keyDown = Input.GetKeyDown("k");

    List<newNumber> numbers = new List<newNumber>();

    if (keyDown)
    {
        numbers.Add(new newNumber(1));
        Debug.Log(numbers);
    }

   if (numbers.Count >= 10)
    {

        Debug.Log("You reached 10!");


   } 

class newNumber
{
    public int _num = 1;

    public newNumber(int num)
    {

        _num = num;

    }
}
  • 1
    How is Numbers() method getting called, each time you call that you are creating a new Numbers List which would wipe out the previous list so your list will always be a length 1 because you add a number then next Numbers call you create new list which clears numbers list. – Bearcat9425 Jun 20 '16 at 13:39
  • It looks like you have left out parts of your source code? How do you call the method Numbers? As you are calling new every time the method is called, the list will never contain more than one element when the if-statement is reached. – Håkan Fahlstedt Jun 20 '16 at 13:41
  • 1
    Store the list outside of the Numbers method as a class variable. Everytime you call new list you are creating a new empty list. Thats why the list never reaches 10 – Marcus Höglund Jun 20 '16 at 13:45
  • @MarcusH That was it. Thank you! – StackFaction Jun 20 '16 at 14:09

1 Answers1

0

You can pass the whole list to your function, and then return it once tasks are finished:

class Number
{
    public int _num = 1;

    public Number(int num)
    {
        _num = num;
    }
}

List<Number> Add_A_Number(List<Number> MyList)
{
    // check condition to add or not
    // .. do your stuff
    // 
    MyList.Add(whatever); // example

    // once finished, return it

    return MyList;
}

B.S: Use proper naming

Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104
  • Underscores in a method name is not proper naming as far as I am aware – TheLethalCoder Jun 20 '16 at 16:18
  • @TheLethal underscores infront of the function name like `_AddANumber` is not proper naming that is 100% correct and here is why: http://stackoverflow.com/questions/783858/underscores-in-function-names – Khalil Khalaf Jun 20 '16 at 16:26