The list visibleItems is successfully filled, but when the TakeItem () is executed, the content is not in place. Although unity shows that the list is full.

Why is this happening and how can this be fixed?

public class Player : Creature { public List<GameObject> visibleItems; public List<GameObject> inventory; void OnTriggerEnter2D(Collider2D coll) { if (coll.gameObject.tag == "Item") { log.text = log.text + "\n " + "Ты видишь " + coll.gameObject.name + "!"; Debug.Log("Ты видишь " + coll.gameObject.name + "!"); visibleItems.Add(coll.gameObject);//объект исправно попадает в visibleItems } } void OnTriggerExit2D(Collider2D coll) { if (coll.gameObject.tag == "Item") { visibleItems.Remove(coll.gameObject);//объект на месте и успешно удаляется } } public void TakeItem()// при вызове метода, список visibleItems отображается в unity заполненным { Debug.Log("TakeItem"); foreach (GameObject o in visibleItems) //список оказывается пустым! { visibleItems.Remove(o); o.SetActive(false); inventory.Add(o); Debug.Log("Ты берешь " + o.gameObject.name); } } } 
  • The code seems to be all right with you. Maybe the state is not updated in the editor as quickly as you want, I have come across such things when debugging. Maybe you will flood the project somewhere and try to take a look - KingPeas

1 answer 1

If it is still relevant, the code will not work, since you are changing the enumerated collection in foreach. I threw a test script on Unity - it falls into an error and swears at the fact that the collection changes when iterating, although maybe your version of Unity swears somehow differently.

Once at the end of the search, visibleItems remains empty, then you can:

 public void TakeItem() { Debug.Log("TakeItem"); foreach (GameObject o in visibleItems) { o.SetActive(false); inventory.Add(o); Debug.Log("Ты берешь " + o.gameObject.name); } visibleItems.Clear(); } 

In addition, if this is not a simplification of the code, it must be remembered that the disabled GameObject enters the inventory list.