Indexoutofrangeexception index was outside the bounds of the array unity как исправить

Здраствуйте, создавал инвентарь для игры и столкнулся с такой ошибкой : “IndexOutOfRangeException: Index was outside the bounds of the array.”

Вот код:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class sobiraenpredmetu : inventoryipob
{
    private inventoryipob inventoey;
    public GameObject slotButton;

    private void Start()
    {
        inventoey = GameObject.FindGameObjectWithTag("Player").GetComponent<inventoryipob>();
    }
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            for (int i = 0; i < inventoey.slots.Length; i++)
            {
                if(idfull[i] == false)
                {
                    idfull[i] = true;
                    Instantiate(slotButton, slots[i].transform);
                    Destroy(gameObject);
                    break;
                }
            }
        }
    }
}

Посмотрел несколько сайтов в интернете, но так и не понял.

Ps. Прошу объяснить подробно, так как я новичок в этом деле.

I have many image in folder screenshots. So this script will be calling the image from folder without applying. But the thing is, the image only displays one image. I mean they did not go to next image like slide show or fade in/out.

Then I keep getting this error message:

IndexOutOfRangeException: Index was outside the bounds of the array.

It points to this code:

ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;

Full code:

Texture2D thisTexture;
byte[] bytes;
string fileName;

public GameObject[] ImageHolder = new GameObject[1];
    
void Start()
    {
        var imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        for (int i = 0; i < imagesToLoad.Length; i++)
    
        {
            thisTexture = new Texture2D(100, 100); //NOW INSIDE THE FOR LOOP
            fileName = imagesToLoad[i];
            bytes = File.ReadAllBytes(fileName);
    
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;
    
    
            // This line
            ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;
        }
    }
}

Here I attached the output. I have 4 RawImage‘s. The image just displays and gets stuck.

enter image description here

asked Dec 22, 2021 at 2:32

chimmy12's user avatar

7

Update!! the error was solved!

I put the variable at image holder

from this

*ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;

to

*ImageHolder[9].GetComponent<RawImage>().texture = thisTexture;

but only display at RawImage(9) and still stuck with one image.

answered Dec 22, 2021 at 3:59

chimmy12's user avatar

As I understood you fill the array ImageHolder with GameObjects in the Editor. Hence you could remove the not relevant and confusing assignment of new GameObject[1] when you initalize the field.

But you should break out of the for loop if your ImageHolder array is shorter than imagesToLoad array.

Or account for it differently by expanding the array and creating new ImageHolders GameObject in which case you probably want to use a list. You could directly reference the RawImage and create a Prefab so you can create and fill your list more easily.

Instead of breaking out of the for loop you could just resize the imagesToLoad array or if you want to use the first use .First() or a select a specific range.

answered Dec 27, 2021 at 0:29

Juri Knauth's user avatar

Juri KnauthJuri Knauth

3591 gold badge4 silver badges11 bronze badges

defoh

1 / 1 / 0

Регистрация: 31.03.2022

Сообщений: 28

1

01.04.2022, 13:14. Показов 1838. Ответов 2

Метки unity, unity 3d (Все метки)


Студворк — интернет-сервис помощи студентам

Возникает такая ошибка IndexOutOfRangeException: Index was outside the bounds of the array.
Character+<play>d__4.MoveNext () (at Assets/Scripts/Character.cs:21)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <d3b66f0ad4e34a55b6ef91ab84878193>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerat or)
Character:Start() (at Assets/Scripts/Character.cs:14)

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Character : MonoBehaviour
{
    SelectedCharacters.Data data = new SelectedCharacters.Data();
    private int i;
    public GameObject[] AllCharacters;
    
    private void Start()
    {
        data = JsonUtility.FromJson<SelectedCharacters.Data>(PlayerPrefs.GetString("SaveGame"));
        StartCoroutine(play());
    }
 
    public IEnumerator play()
    {
            i = 0;
 
            while (AllCharacters[i].name != data.currentCharacter)
            {
                i++;
            }
            AllCharacters[i].SetActive(true);
            yield return null;
        
    }
}



0



Алексанierecumi

95 / 60 / 36

Регистрация: 07.08.2013

Сообщений: 241

01.04.2022, 13:47

2

у вас [i] не ограничено длинной массива

C#
1
if (i <= AllCharacters.Length) { };



0



BattleCrow

559 / 361 / 206

Регистрация: 18.10.2019

Сообщений: 1,217

01.04.2022, 20:09

3

defoh, судя по всему возникает ситуация, когда в массиве нет объекта, который бы противоречил этому условию:

Цитата
Сообщение от defoh
Посмотреть сообщение

while (AllCharacters[i].name != data.currentCharacter)

Чтобы избежать ошибки, можно написать так:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    public IEnumerator play()
    {
            i = 0;
 
            while (AllCharacters[i].name != data.currentCharacter && i < AllCharacters.Length)
            {
                i++;
            }
            if(i == AllCharacters.Length)
                Debug.Log("Искомый объект отсутствует в массиве!");
            else
                AllCharacters[i].SetActive(true);
 
            yield return null;       
    }



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

01.04.2022, 20:09

Помогаю со студенческими работами здесь

IndexOutOfRangeException: Index was outside the bounds of the array. (ошибка в коде)
Всем привет, возникает вот такая ошибка в коде: &quot;IndexOutOfRangeException: Index was outside the…

Ошибка – Runtime exception: System.IndexOutOfRangeException: Index out of the bounds of the array
Всем привет, помогите пожалуйста решить ошибку – Runtime exception:…

Выдает такую ошибку IndexOutOfRangeException: Index was outside the bounds of the array. Бьюсь уже 3 час над решением
IndexOutOfRangeException: Index was outside the bounds of the array.
SelectedCharacter.ArrowRight…

Ошибка Index was outside the bounds of the array. Как исправить?
Пытаюсь написать простую программу по выводу массива на экран. Visual Studio показывает 0 ошибок,…

Ошибка System.IndexOutOfRangeException: “Index was outside the bounds of the array”
Юнити. Есть трёхмерный массив, есть цикл. Но я не понимаю, почему на 34 строке появляется…

Ошибка System.IndexOutOfRangeException: “Index was outside the bounds of the array”
В двумерном массиве A=(a1, а2, …, аn) отрицательные элементы, имеющие четный порядковый номер,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

3

Quote:

I am getting an error like IndexOutOfRangeException: Index was outside the bounds of array.

The complete error message also tells you the position of error, it is a good idea to tell us too.
No matter where is the error, your code try to read/write an item of an array that does not exist. One tool can help you to understand what is wrong, it is the debugger.

Your code do not behave the way you expect, or you don’t understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don’t know what your code is supposed to do, it don’t find bugs, it just help you to by showing you what is going on. When the code don’t do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger – Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 – A Beginner’s Guide[^]
Basic Debugging with Visual Studio 2010 – YouTube[^]

Debugging C# Code in Visual Studio – YouTube[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.

IndexOutOfRangeException: Index was outside the bounds of the array.
  at UnityEngine.Experimental.Input.InputActionMapState.ChangePhaseOfAction (UnityEngine.Experimental.Input.InputActionPhase newPhase, UnityEngine.Experimental.Input.InputActionMapState+TriggerState& trigger, UnityEngine.Experimental.Input.InputActionPhase phaseAfterPerformedOrCancelled) [0x000d6] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:845 
  at UnityEngine.Experimental.Input.InputActionMapState.ProcessControlStateChange (System.Int32 mapIndex, System.Int32 controlIndex, System.Int32 bindingIndex, System.Double time, UnityEngine.Experimental.Input.LowLevel.InputEventPtr eventPtr) [0x00152] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:569 
  at UnityEngine.Experimental.Input.InputActionMapState.UnityEngine.Experimental.Input.LowLevel.IInputStateChangeMonitor.NotifyControlStateChanged (UnityEngine.Experimental.Input.InputControl control, System.Double time, UnityEngine.Experimental.Input.LowLevel.InputEventPtr eventPtr, System.Int64 mapControlAndBindingIndex) [0x0000f] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:455 
  at UnityEngine.Experimental.Input.InputManager.FireStateChangeNotifications (System.Int32 deviceIndex, System.Double internalTime, UnityEngine.Experimental.Input.LowLevel.InputEvent* eventPtr) [0x00078] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemInputManager.cs:2963 
  at UnityEngine.Experimental.Input.InputManager.OnUpdate (UnityEngine.Experimental.Input.InputUpdateType updateType, UnityEngine.Experimental.Input.LowLevel.InputEventBuffer& eventBuffer) [0x00936] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemInputManager.cs:2693 
  at UnityEngine.Experimental.Input.LowLevel.NativeInputRuntime+<>c__DisplayClass6_0.<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType updateType, System.Int32 eventCount, System.IntPtr eventPtr) [0x00011] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemNativeInputRuntime.cs:110 
  at UnityEngineInternal.Input.NativeInputSystem.NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType updateType, System.Int32 eventCount, System.IntPtr eventData) [0x00011] in C:buildslaveunitybuildModulesInputPrivateInput.cs:91 
 
(Filename: Library/PackageCache/com.unity.inputsystem@0.1.2-preview/InputSystem/Actions/InputActionMapState.cs Line: 845)

IndexOutOfRangeException: Index was outside the bounds of the array.
  at UnityEngine.Experimental.Input.InputActionMapState.GetActionOrNull (UnityEngine.Experimental.Input.InputActionMapState+TriggerState& trigger) [0x00091] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:985 
  at UnityEngine.Experimental.Input.InputActionMapState.GetActionOrNoneString (UnityEngine.Experimental.Input.InputActionMapState+TriggerState& trigger) [0x00001] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:954 
  at UnityEngine.Experimental.Input.InputActionMapState.ThrowIfPhaseTransitionIsInvalid (UnityEngine.Experimental.Input.InputActionPhase currentPhase, UnityEngine.Experimental.Input.InputActionPhase newPhase, UnityEngine.Experimental.Input.InputActionMapState+TriggerState& trigger) [0x0006e] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:938 
  at UnityEngine.Experimental.Input.InputActionMapState.ChangePhaseOfAction (UnityEngine.Experimental.Input.InputActionPhase newPhase, UnityEngine.Experimental.Input.InputActionMapState+TriggerState& trigger, UnityEngine.Experimental.Input.InputActionPhase phaseAfterPerformedOrCancelled) [0x00099] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:837 
  at UnityEngine.Experimental.Input.InputActionMapState.ProcessControlStateChange (System.Int32 mapIndex, System.Int32 controlIndex, System.Int32 bindingIndex, System.Double time, UnityEngine.Experimental.Input.LowLevel.InputEventPtr eventPtr) [0x00152] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:569 
  at UnityEngine.Experimental.Input.InputActionMapState.UnityEngine.Experimental.Input.LowLevel.IInputStateChangeMonitor.NotifyControlStateChanged (UnityEngine.Experimental.Input.InputControl control, System.Double time, UnityEngine.Experimental.Input.LowLevel.InputEventPtr eventPtr, System.Int64 mapControlAndBindingIndex) [0x0000f] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemActionsInputActionMapState.cs:455 
  at UnityEngine.Experimental.Input.InputManager.FireStateChangeNotifications (System.Int32 deviceIndex, System.Double internalTime, UnityEngine.Experimental.Input.LowLevel.InputEvent* eventPtr) [0x00078] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemInputManager.cs:2963 
  at UnityEngine.Experimental.Input.InputManager.OnUpdate (UnityEngine.Experimental.Input.InputUpdateType updateType, UnityEngine.Experimental.Input.LowLevel.InputEventBuffer& eventBuffer) [0x00936] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemInputManager.cs:2693 
  at UnityEngine.Experimental.Input.LowLevel.NativeInputRuntime+<>c__DisplayClass6_0.<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType updateType, System.Int32 eventCount, System.IntPtr eventPtr) [0x00011] in J:MazeLibraryPackageCachecom.unity.inputsystem@0.1.2-previewInputSystemNativeInputRuntime.cs:110 
  at UnityEngineInternal.Input.NativeInputSystem.NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType updateType, System.Int32 eventCount, System.IntPtr eventData) [0x00011] in C:buildslaveunitybuildModulesInputPrivateInput.cs:91 
 
(Filename: Library/PackageCache/com.unity.inputsystem@0.1.2-preview/InputSystem/Actions/InputActionMapState.cs Line: 985)

Добавить комментарий