- Home /
I figured it out.
Interchangeable value loop
for (int i = 0; i < myList.Count; i++)
{
if (myList[i] == null)
{
myList[i] = item;
break;
}
}
I want "i" to be an interchangeable number i.e. if I have 5 items I want 5 items to be added to myList. If have 7 it adds 7 etc.
Sure thing. What do you want me to elaborate on?
Right now "i" is used to iterate trough the list, i don't get how would it be interchangeable. What should dictate how many elements to add to the list?
Answer by pauldarius98 · Mar 02, 2021 at 09:34 PM
Ok, after the informations that you provides me i think i figured out what you need. So, in order to add an item to your list you can use myList.Add(item)
If you want to add an item n times you can write
for (int i= 0; i < n; i++)
{
myList.Add(item);
}
Where n is the number of times to add the item
No, that's not it. This is how I mean:
int value = 1;
for (int i= 0; i < 10; i++)
{
myList.Add(item);
}
Value is interchangeable, meaning, it isn't always going to be 1. But I want value to dictate how many item(s) get added. So if value = 4. The myList.Add(item) * 4.
Well, you can set n to how many items you want to be added, just declare it like int n = 4; place whatever value that you need instead of 4. You can also change the value at runtime from code
No, I just keep getting "ArgumentOutOfRangeException: Argument is out of range."
Your "value" is the variable "n" in paul's answer and his code does exactly that. If n == 4 the boop body will run 4 times. If you have trouble understanding how a for loop works I highly recommend you watch some general basic coding tutorials. Those are the absolute fundametal basics.
A for loop header has exactly 3 parts:
the initialization part
the for loop condition
the loop step postprocessing part.
A loop like this:
for(int i = 0; i < n; i++)
{
// code
}
Will roughly translate to a while loop that looks like this:
{
int i = 0;
while (i < n)
{
// code
i++;
}
}
I understand how loops work. It's just not the result I'm looking for. I'm explaining my problem as best I can but I don't know how to make it any clearer. I don't want "n" to change. "n" should stay the same size. I tried making it a nested loop like this:
for (int x = 0; x < value; x++)
{
for (int i = 0; i < n; i++)
{
if (myList[i] == null)
{
myList.Add(item);
break;
}
}
}
But this doesn't work either even though I believe it should.
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Loop through a GameObject list based on the size of the list 1 Answer
Vector3 List Find Contains Specific X Coordinate Value and Remove 0 Answers
Default value on List vanished 3 Answers
How to have a loop run itself again if returned value is a known exception, with a new return value. 1 Answer