- Home /
Always adds items to list
Hi,i made a list where i store some gameobjects. The gameobjects in the list are sorted by the distance from the player (if i'm not clear i mean element 0: nearest object to player,element 1:2nd nearest object to player etc.)When the player reaches the element 0 of the list this element is removed from the list and stored in another "trash" list. The problem is when i add the item in the trash list,it adds the element at every frame and it should add it once.
public List listMete = new List(); //list that stores gameobject to reach
public List listMeteTrash = new List()//trash list,stores reached gameobjects
void Update()
{
if (transform.position == listMete[0].transform.position)
{
for(int i=0;i<1;i++)
{
listMeteTrash.Add(listMete[0]);
listMete.Remove(listMete[0]); //here works correctly
}
}
}
Thanks in advance guys! :D
Answer by richyrich · Dec 15, 2014 at 12:42 AM
//for(int i=0;i<1;i++)
//{
listMeteTrash.Add(listMete[0]);
listMete.RemoveAt(0);
//}
The for loop iterates once, so remove
If after removing the zeroth element, you are then updating the transform position to the new zeroeth element, the problem will persist
Thank you for your answer but it didn't change anything,the code always adds the item to the trash list,the problem is in list$$anonymous$$eteTrash.Add(list$$anonymous$$ete[0]);
There is limited information to go on from what you have provided.
If the player position is set to equal the nearest GameObject, then the remove will naturally occur every update. It would be useful to see the code that decides whether to update the position as that is what is likely responsible for the problem