'how do i remove an index from an array in unity
I got this code:
string[] changedHobbyList = listOfHobbies;
string[] finishedHobbyList = new string[3];
for (int i = 0; i < 3; i++)
{
int num = Random.Range(0, changedHobbyList.Length-1);
finishedHobbyList[i] = changedHobbyList[num];
for (int l = num -1 ; l < changedHobbyList.Length; l++)
{
changedHobbyList[l] = changedHobbyList[l+1];
}
}
from https://www.includehelp.com/dot-net/delete-an-element-from-given-position-from-array-using-c-sharp-program.aspx and I am getting an index out of bounds error and I know how im getting it, but I cant figure out a way to fix it, as well as just getting it working, so if you have a better idea, please and thank you
Solution 1:[1]
string[] changedList = new string[] {"hi,"cheese","more cheese"};
string[] changingList = new string[changedList.Length-1];
int num = *index being removed*;
int spot = 0;
for (int l = 0; l < changedList.Length; l++)
{
if (l != num){
changingList[spot] = changedList[l];
spot++;
changedList = changingList;
}
this is basically creating a new list and then replacing it with the name of the one you inputed
Solution 2:[2]
What value is num? What is the lengths of your two arrays?
Your for loop looks like it's shifting everything from right to left by one. It's possible you're going out of bounds because your listOfHobbies length is greater than changedHobbies which could happen at changedHobbyList[l+1].
EDIT:
After reviewing the revised loop, it's because of your check in the for loop
l < changedHobbyList.Length
You're going out of bounds when l is 1 less than the length and you access the array like:
intArray[l+1];
consider changing it to:
for (int l = num -1 ; l < changedHobbyList.Length - 1; l++)
{
changedHobbyList[l] = changedHobbyList[l+1];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LeeLime5000 |
| Solution 2 |
