Indexoutofrangeexception array index is out of range

Indexoutofrangeexception array index is out of range

IndexOutOfRangeException: Array index is out of range. WordScramble.ShowScramble (Int32 index, Int32 index2) (at Assets/Word Sramble/WordScramble.cs:210) WordScramble.Start () (at Assets/Word Sramble/WordScramble.cs:134)

1 Answer 1

The index check is not done properly. There needs to be an OR operation instead. Otherwise both indexes need to be out of range to satisfy the condition.

if ((index > words.Length — 1) || (index2 > questions.Length — 1))

It might be a good idea to include testing for negative numbers:

if ((index > words.Length — 1) || (index2 > questions.Length — 1) || index

Your not using the chars2 array in the following code, so consider maybe changing the code appropriately. But I guess it all depends on what you want the code to do.

Определение

Исключение, возникающее при попытке обращения к элементу массива или коллекции с индексом, который находится вне границ. The exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds.

Комментарии

IndexOutOfRangeException Исключение возникает, когда недопустимый индекс используется для доступа к члену массива или коллекции либо для чтения или записи из определенного расположения в буфере. An IndexOutOfRangeException exception is thrown when an invalid index is used to access a member of an array or a collection, or to read or write from a particular location in a buffer. Это исключение наследуется от Exception класса, но не добавляет уникальных членов. This exception inherits from the Exception class but adds no unique members.

Как правило, IndexOutOfRangeException исключение возникает в результате ошибки разработчика. Typically, an IndexOutOfRangeException exception is thrown as a result of developer error. Вместо обработки исключения следует диагностировать причину ошибки и исправить код. Instead of handling the exception, you should diagnose the cause of the error and correct your code. Наиболее частые причины этой ошибки: The most common causes of the error are:

При этом не забывают, что верхняя граница коллекции или массива, начинающегося с нуля, является на единицу меньше, чем число элементов или элементов, как показано в следующем примере. Forgetting that the upper bound of a collection or a zero-based array is one less than its number of members or elements, as the following example illustrates.

Чтобы исправить эту ошибку, можно использовать код, подобный приведенному ниже. To correct the error, you can use code like the following.

Кроме того, вместо итерации всех элементов массива по индексу можно использовать foreach оператор (в C#) или For Each оператор (в Visual Basic). Alternately, instead of iterating all the elements in the array by their index, you can use the foreach statement (in C#) or the For Each statement (in Visual Basic).

Попытка присвоить элемент массива другому массиву, не имеющему достаточного размера и имеющему меньше элементов, чем исходный массив. Attempting to assign an array element to another array that has not been adequately dimensioned and that has fewer elements than the original array. В следующем примере предпринимается попытка присвоить value1 последний элемент в массиве тому же value2 элементу в массиве. The following example attempts to assign the last element in the value1 array to the same element in the value2 array. Однако массив был value2 неправильно распределен, так как он имеет шесть вместо семи элементов. However, the value2 array has been incorrectly dimensioned to have six instead of seven elements. В результате присваивание вызывает IndexOutOfRangeException исключение. As a result, the assignment throws an IndexOutOfRangeException exception.

Использование значения, возвращаемого методом поиска для итерации части массива или коллекции, начиная с определенной позиции индекса. Using a value returned by a search method to iterate a portion of an array or collection starting at a particular index position. Если вы забыли проверить, нашел ли операция поиска совпадение, среда выполнения выдаст IndexOutOfRangeException исключение, как показано в этом примере. If you forget to check whether the search operation found a match, the runtime throws an IndexOutOfRangeException exception, as shown in this example.

Читайте также:  Как поменять тайминги оперативной памяти в биосе

В этом случае List .IndexOf метод возвращает значение-1, которое является недопустимым значением индекса, когда не удается найти соответствие. In this case, the List .IndexOf method returns -1, which is an invalid index value, when it fails to find a match. Чтобы исправить эту ошибку, проверьте возвращаемое значение метода поиска перед перебором массива, как показано в этом примере. To correct this error, check the search method’s return value before iterating the array, as shown in this example.

Попытка использовать или перечислить результирующий набор, коллекцию или массив, возвращенные запросом, не проверяя, содержит ли возвращаемый объект какие-либо допустимые данные. Trying to use or enumerate a result set, collection, or array returned by a query without testing whether the returned object has any valid data.

Использование вычисленного значения для определения начального индекса, конечного индекса или числа элементов для итерации. Using a computed value to define the starting index, the ending index, or the number of items to be iterated. Если результат вычисления является непредвиденным, это может привести к IndexOutOfRangeException исключению. If the result of the computation is unexpected, it might result in an IndexOutOfRangeException exception. Необходимо проверить логику программы в вычислении значения индекса и проверить значение перед перебором массива или коллекции. You should check your program’s logic in calculating the index value and validate the value before iterating the array or collection. Все следующие условия должны иметь значение true. в противном случае возникает исключение:IndexOutOfRangeException The following conditions must all be true; otherwise, an IndexOutOfRangeException exception is thrown:

Начальный индекс должен быть больше или равен значению Array.GetLowerBound для измерения массива, для которого необходимо выполнить итерацию, или больше или равно 0 для коллекции. The starting index must be greater than or equal to Array.GetLowerBound for the dimension of the array that you want to iterate, or greater than or equal to 0 for a collection.

Конечный индекс не может превышать Array.GetUpperBound размер массива, который необходимо пробрать, или не может быть больше или равен Count свойству коллекции. The ending index cannot exceed Array.GetUpperBound for the dimension of the array that you want to iterate, or cannot be greater than or equal to the Count property of a collection.

Следующее уравнение должно иметь значение true для измерения массива, который необходимо пробрать: The following equation must be true for the dimension of the array that you want to iterate:

Для коллекции должно быть истинно следующее уравнение: For a collection, the following equation must be true:

Начальный индекс массива или коллекции никогда не может быть отрицательным числом. The starting index of an array or collection can never be a negative number.

Предполагается, что массив должен относиться от нуля. Assuming that an array must be zero-based. Массивы, не основанные на нуле, могут быть созданы Array.CreateInstance(Type, Int32[], Int32[]) методом и могут возвращаться COM-взаимодействием, хотя они не являются CLS-совместимыми. Arrays that are not zero-based can be created by the Array.CreateInstance(Type, Int32[], Int32[]) method and can be returned by COM interop, although they aren’t CLS-compliant. В следующем примере показано IndexOutOfRangeException , что вызывается при попытке выполнить итерацию массива, отличного от нуля, созданного Array.CreateInstance(Type, Int32[], Int32[]) методом. The following example illustrates the IndexOutOfRangeException that is thrown when you try to iterate a non-zero-based array created by the Array.CreateInstance(Type, Int32[], Int32[]) method.

Чтобы исправить ошибку, как показано в следующем примере, можно вызвать GetLowerBound метод, а не делать предположения о начальном индексе массива. To correct the error, as the following example does, you can call the GetLowerBound method instead of making assumptions about the starting index of an array.

Читайте также:  Pascal to c converter online

Обратите внимание, что при GetLowerBound вызове метода для получения начального индекса массива необходимо также Array.GetUpperBound(Int32) вызвать метод, чтобы получить его конечный индекс. Note that when you call the GetLowerBound method to get the starting index of an array, you should also call the Array.GetUpperBound(Int32) method to get its ending index.

Путаница с индексом и значением в этом индексе в числовом массиве или коллекции. Confusing an index and the value at that index in a numeric array or collection. Эта проблема обычно возникает при использовании foreach оператора (в C#) или For Each оператора (в Visual Basic). This issue usually occurs when using the foreach statement (in C#) or the For Each statement (in Visual Basic). В следующем примере показана эта проблема. The following example illustrates the problem.

Конструкция итерации возвращает каждое значение в массиве или коллекции, а не в его индексе. The iteration construct returns each value in an array or collection, not its index. Чтобы устранить исключение, используйте этот код. To eliminate the exception, use this code.

Указание недопустимого имени столбца для DataView.Sort свойства. Providing an invalid column name to the DataView.Sort property.

Нарушение безопасности потоков. Violating thread safety. Такие операции, как чтение из одного StreamReader и того же объекта, запись StreamWriter в один и тот же объект из нескольких потоков или перечисление объектов Hashtable из различных потоков, IndexOutOfRangeException могут вызывать исключение, если доступ к объекту не осуществляется в потокобезопасный способ. Operations such as reading from the same StreamReader object, writing to the same StreamWriter object from multiple threads, or enumerating the objects in a Hashtable from different threads can throw an IndexOutOfRangeException if the object isn’t accessed in a thread-safe way. Обычно это исключение периодически, так как оно зависит от состояния гонки. This exception is typically intermittent because it relies on a race condition.

Использование жестко заданных индексных значений для работы с массивом, скорее всего, вызовет исключение, если значение индекса неверно или недопустимо, или если размер обрабатываемого массива является непредвиденным. Using hard-coded index values to manipulate an array is likely to throw an exception if the index value is incorrect or invalid, or if the size of the array being manipulation is unexpected. Чтобы предотвратить создание IndexOutOfRangeException исключения операцией, можно выполнить следующие действия. To prevent an operation from throwing an IndexOutOfRangeException exception, you can do the following:

Выполните итерацию элементов массива с помощью оператора foreach (в C#) или объекта For Each. Следующая конструкция (в Visual Basic) вместо итерации элементов по индексу. Iterate the elements of the array using the foreach statement (in C#) or the For Each. Next construct (in Visual Basic) instead of iterating elements by index.

Выполните итерацию элементов по индексу, начиная с индекса, Array.GetLowerBound возвращенного методом, и заканчивая индексом Array.GetUpperBound , возвращенным методом. Iterate the elements by index starting with the index returned by the Array.GetLowerBound method and ending with the index returned by the Array.GetUpperBound method.

При назначении элементов в одном массиве убедитесь, что целевой массив имеет по крайней мере столько же элементов, что и исходный массив, путем сравнения Array.Length их свойств. If you are assigning elements in one array to another, ensure that the target array has at least as many elements as the source array by comparing their Array.Length properties.

Список начальных значений свойств для экземпляра IndexOutOfRangeException, см. в разделе IndexOutOfRangeException конструкторы. For a list of initial property values for an instance of IndexOutOfRangeException, see the IndexOutOfRangeException constructors.

Читайте также:  Геометрические формы для рисования

Следующие инструкции промежуточного языка (IL) вызовут IndexOutOfRangeException: The following intermediate language (IL) instructions throw IndexOutOfRangeException:

IndexOutOfRangeExceptionиспользует HRESULT COR_E_INDEXOUTOFRANGE, имеющий значение 0x80131508. IndexOutOfRangeException uses the HRESULT COR_E_INDEXOUTOFRANGE, which has the value 0x80131508.

Конструкторы

Инициализирует новый экземпляр класса IndexOutOfRangeException. Initializes a new instance of the IndexOutOfRangeException class.

Инициализирует новый экземпляр класса IndexOutOfRangeException с указанным сообщением об ошибке. Initializes a new instance of the IndexOutOfRangeException class with a specified error message.

Инициализирует новый экземпляр класса IndexOutOfRangeException указанным сообщением об ошибке и ссылкой на внутреннее исключение, вызвавшее данное исключение. Initializes a new instance of the IndexOutOfRangeException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Свойства

Возвращает коллекцию пар ключ/значение, предоставляющие дополнительные сведения об исключении, определяемые пользователем. Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Унаследовано от Exception)

HelpLink

Получает или задает ссылку на файл справки, связанный с этим исключением. Gets or sets a link to the help file associated with this exception.

(Унаследовано от Exception)

HResult

Возвращает или задает HRESULT — кодированное числовое значение, присвоенное определенному исключению. Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Унаследовано от Exception)

InnerException

Возвращает экземпляр класса Exception, который вызвал текущее исключение. Gets the Exception instance that caused the current exception.

(Унаследовано от Exception)

Message

Возвращает сообщение, описывающее текущее исключение. Gets a message that describes the current exception.

(Унаследовано от Exception)

Source

Возвращает или задает имя приложения или объекта, вызывавшего ошибку. Gets or sets the name of the application or the object that causes the error.

(Унаследовано от Exception)

StackTrace

Получает строковое представление непосредственных кадров в стеке вызова. Gets a string representation of the immediate frames on the call stack.

(Унаследовано от Exception)

TargetSite

Возвращает метод, создавший текущее исключение. Gets the method that throws the current exception.

(Унаследовано от Exception)

Методы

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object)

GetBaseException()

При переопределении в производном классе возвращает исключение Exception, которое является корневой причиной одного или нескольких последующих исключений. When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Унаследовано от Exception)

GetHashCode()

Служит в качестве хэш-функции по умолчанию. Serves as the default hash function.

(Унаследовано от Object)

GetObjectData(SerializationInfo, StreamingContext)

При переопределении в производном классе задает сведения об исключении для SerializationInfo. When overridden in a derived class, sets the SerializationInfo with information about the exception.

(Унаследовано от Exception)

GetType()

Возвращает тип среды выполнения текущего экземпляра. Gets the runtime type of the current instance.

(Унаследовано от Exception)

MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object)

ToString()

Создает и возвращает строковое представление текущего исключения. Creates and returns a string representation of the current exception.

(Унаследовано от Exception)

События

Возникает, когда исключение сериализовано для создания объекта состояния исключения, содержащего сериализованные данные об исключении. Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

Выдаёт ошибку IndexOutOfRangeException: Array index is out of range.
Вот первый скрипт

ошибка в
posX[i] = enemy[i].transform.position.x;

Вот второй скрипт

Помогите, в чем ошибка?

  • Вопрос задан более трёх лет назад
  • 1979 просмотров

Где инициализация public float[] posY;
posY = new float[. ]

for (int i = 1; i == length; i++)
Это вообще что такое?
Если enemy.length = 1, то есть длина массива 1, то enemy[0] выдаст объект,а enemy[1] как раз то исключение.

Может быть
for (int i = 0; i более трёх лет назад

Ссылка на основную публикацию
Adblock
detector