Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Using an int as the size of a list

Discussion in 'Scripting' started by All_American, Feb 10, 2021.

  1. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    Any idea how to make a list the size of an int?

    I am racking my brain trying to do this.

    I have an object that is an int. It gets set by inputfield and I want to use it to instantiate an object however many times the int is.
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    When creating a new List, you can add a int parameter as the starting capacity:
    Code (CSharp):
    1. //Create a new List with a starting capacity of 10.
    2. var whatever = new List<whatever>(10);
    This is not a hard-cap though - you can still add items over the starting capacity. If you want to have a hard-cap of elements, use an array instead.

    Use a for-loop:
    Code (CSharp):
    1. int instantiateCount = 5;
    2.  
    3. //Instantiate will be looped over 5 times.
    4. for(int i = 0; i < instantiateCount; i++) {
    5.    Instantiate(/*your object*/);
    6. }
    Not sure how the two questions here relate to each other though.
     
  3. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    @Vrken

    The first part of my post was what I need. The second part is what I want to do.

    You did it. I hadn't thought of that. Thank you.
     
    Kurt-Dekker likes this.