- Home /
TileBase array conversion to list not clearing?
Hi, I don't post here often so sorry if my format is a bit messed up. I am using System.Linq to change the array over to a list and then attempting to clear everything that is null inside the list. I've only just started using tilemaps and have noticed that a lot of tilemaps in my array are null. so I put them into a list to clear them out. This for some reason only clears out half of the list. Here is my code.
BoundsInt bounds = myNodesTilemap.cellBounds;
TileBase[] allTiles = myNodesTilemap.GetTilesBlock(bounds);
tempTileList = allTiles.ToList<TileBase>();
for (int i = 0; i < tempTileList.Count; i++)
{
if (tempTileList[i] == null)
{
tempTileList.RemoveAt(i);//this only removes half of the list, if I don't run this line of code I get a list of 48. If I run it I get a list of 24.
}
if (tempTileList[i] != null)
{
Debug.Log(tempTileList[i].name);//this never debugs anything.
}
}
Answer by ShadyProductions · Jul 08, 2018 at 09:11 AM
allTiles.Where(f => f != null).ToList();
Should be enough using LINQ.
Iterating over a list / array and removing indexes has weird side effects, This because say you are looping over a list of 10 objects, you remove one, and you have 9 left while you are looping over 10 objects which can cause index out of range issues and its not even permitted in foreach loops, on for loops it re evaluates the initial loop accessing the list's .Count as you are using which is why it does not throw an index out of range exception but still gives you weird results. It would be better to ins$$anonymous$$d loop over a list and add all values that are not null to a new list and return that. But this is the easier way since you're already intending to use .ToList from LINQ. $$anonymous$$ight aswel use its where predicate.