Limit the size/capacity of a list

I tried setting the listname.capacity in both start and update and even tried listname.capacity.set but it doesn’t exist

hi there

try this

    public Unit unit;

    public int armyCapacityLimit = 10;

    public void RecruitUnits()
    {
        if (armyCapacity.Count < 10)
            armyCapacity.Add(unit);
        else
            return;
    }

Hi

The list ‘capacity’ does not place a fixed size on the list - it is there to tell you how many items the list could currently store without allocating more memory (as it allocates memory out in blocks). When you set it, you are telling the list ‘I expect there to be this many items’ - it’s a hint to avoid lots of little memory allocations.

Is no in built function to add to a list without going over a certain size - indeed, the whole point of ‘List’ is that it is a dynamically sizing array!

If you want fixed size behaviour you’ll either want to:

  • just use an array (though this doesn’t behave quite like a list)
  • write your own function that only adds to the list if it is not already full

-Chris

For a fixed size, consider using an array, If for whatever reason you do really want a list. then you need to encapsulate access to the list so that you can force a size restriction when you try to add to the list.