简体   繁体   中英

Unity3D ArgumentOutOfRangeException: Index was out of range

I have a problem with my code. Compiler stop on this line when I try to pick up the object.

ekwipunek.ListaNaszychPrzedmiotow[i] = BazaDanych_Eq.ListaPrzedmiotow [IdPrzedmiotu];

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

if ( Input.GetKeyDown (KeyCode.Q))
{
    IdPrzedmiotu = DoPodniesienia.GetComponent<PrzedmiotPodniesienie>().id;
    for (int i = 0; i < ekwipunek.ListaNaszychPrzedmiotow.Count; i++)
    {
        if (ekwipunek.ListaNaszychPrzedmiotow[i].id == 0 && DoPodniesienia != null)
        {
            ekwipunek.ListaNaszychPrzedmiotow[i] = BazaDanych_Eq.ListaPrzedmiotow [IdPrzedmiotu];
            Destroy(DoPodniesienia);
            DoPodniesienia = null;
         }
     }
}

Your problem, more than likely, exists because one of your indices on this line references something that would be outside of the range of the collection.

You're setting this variable that is used as an index to an id.

 IdPrzedmiotu = DoPodniesienia.GetComponent<PrzedmiotPodniesienie>().id;

Then, you're referencing it further down without verifying that it is available in your collection.

 BazaDanych_Eq.ListaPrzedmiotow [IdPrzedmiotu]

You need to validate this value or this collection before accessing it.


Future Debugging Tip: ArgumentOutOfRangeException

  • Check the count of any collection you are using
  • Check the value of any index you will use to reference the collection

public class YourClass
{
    ...
    Debug.Log($"The collection \"ListaNaszychPrzedmiotow\" is {ListaNaszychPrzedmiotow.Count()}");
    Debug.Log($"The index value of \"i\" is {i}");
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM