Здраствуйте, создавал инвентарь для игры и столкнулся с такой ошибкой : “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.
asked Dec 22, 2021 at 2:32
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
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 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.
0 |
Алексанierecumi 95 / 60 / 36 Регистрация: 07.08.2013 Сообщений: 241 |
||||
01.04.2022, 13:47 |
2 |
|||
у вас [i] не ограничено длинной массива
0 |
BattleCrow 559 / 361 / 206 Регистрация: 18.10.2019 Сообщений: 1,217 |
||||
01.04.2022, 20:09 |
3 |
|||
defoh, судя по всему возникает ситуация, когда в массиве нет объекта, который бы противоречил этому условию:
while (AllCharacters[i].name != data.currentCharacter) Чтобы избежать ошибки, можно написать так:
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. (ошибка в коде) Ошибка – Runtime exception: System.IndexOutOfRangeException: Index out of the bounds of the array Выдает такую ошибку IndexOutOfRangeException: Index was outside the bounds of the array. Бьюсь уже 3 час над решением Ошибка Index was outside the bounds of the array. Как исправить? Ошибка System.IndexOutOfRangeException: “Index was outside the bounds of the array” Ошибка System.IndexOutOfRangeException: “Index was outside the bounds of the array” Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 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)