简体   繁体   English

Unity3D ArgumentOutOfRangeException:索引超出范围

[英]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. ArgumentOutOfRangeException:索引超出范围。 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. 您正在设置此变量,用作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 未来的调试提示: 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}");
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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