Форум программистов, компьютерный форум, киберфорум
Unity, Unity3D
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.82/11: Рейтинг темы: голосов - 11, средняя оценка - 4.82
1 / 1 / 0
Регистрация: 31.03.2022
Сообщений: 28

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

31.03.2022, 20:50. Показов 2174. Ответов 3

Студворк — интернет-сервис помощи студентам
IndexOutOfRangeException: Index was outside the bounds of the array.
SelectedCharacter.ArrowRight () (at Assets/Scripts/SelectedCharacter.cs:51)
UnityEngine.Events.InvokableCall.Invoke () (at <d3b66f0ad4e34a55b6ef91ab84878193>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <d3b66f0ad4e34a55b6ef91ab84878193>:0)
UnityEngine.UI.Button.Press () (at B:/Unity ME/Ruuner/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:68)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventDa ta eventData) (at B:/Unity ME/Ruuner/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:110)
UnityEngine.EventSystems.ExecuteEvents.E xecute (UnityEngine.EventSystems.IPointerClickH andler handler, UnityEngine.EventSystems.BaseEventData eventData) (at B:/Unity ME/Ruuner/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.E xecute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+E ventFunction`1[T1] functor) (at B:/Unity ME/Ruuner/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:262)
UnityEngine.EventSystems.EventSystem:Upd ate() (at B:/Unity ME/Ruuner/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:385)
Код вот такой ->
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class SelectedCharacter : MonoBehaviour
{
    private int i;
    private int currentCharacter;
    public GameObject[] AllCharacters;
    public GameObject ArrowToLeft;
    public GameObject ArrowToRight;
    public GameObject ButtonSelectCharacter;
    public GameObject TextSelectCharacter;
    private void Start()
    {
        if (PlayerPrefs.HasKey("CurrentCharacter"))
        {
            i = PlayerPrefs.GetInt("CurrentCharacter");
            currentCharacter = PlayerPrefs.GetInt("CurrentCharacter");
 
        }
        else
        {
            PlayerPrefs.SetInt("CurrentCharacter", i);
        }
        AllCharacters[i].SetActive(true);
        ButtonSelectCharacter.SetActive(false);
        TextSelectCharacter.SetActive(true);
 
        if (i > 0)
        {
            ArrowToLeft.SetActive(true);
        }
        if (i == AllCharacters.Length)
        {
            ArrowToRight.SetActive(false);
        }
    }
 
    public void ArrowRight()
    {
        if (i < AllCharacters.Length)
        {
            if (i == 0)
            {
                ArrowToLeft.SetActive(true);
            }
            AllCharacters[i].SetActive(false);
            i++;
            AllCharacters[i].SetActive(true);
            if (currentCharacter == i)
            {
                ButtonSelectCharacter.SetActive(false);
                TextSelectCharacter.SetActive(true);
            }
            else
            {
                ButtonSelectCharacter.SetActive(true);
                TextSelectCharacter.SetActive(false);
            }
            if (i + 1 == AllCharacters.Length)
            {
                ArrowToRight.SetActive(false);
            }
        }
    }
    public void ArrowLeft()
    {
        if (i < AllCharacters.Length)
        {
            AllCharacters[i].SetActive(false);
            i--;
            AllCharacters[i].SetActive(true);
            ArrowToRight.SetActive(true);
            if (currentCharacter == i)
            {
                ButtonSelectCharacter.SetActive(false);
                TextSelectCharacter.SetActive(true);
            }
            else
            {
                ButtonSelectCharacter.SetActive(true);
                TextSelectCharacter.SetActive(false);
            }
            if (i == 0)
            {
                ArrowToLeft.SetActive(false);
            }
        }
    }
    public void SelectCharacter()
    {
        PlayerPrefs.SetInt("CurrentCharacter", i);
        currentCharacter = i;
        ButtonSelectCharacter.SetActive(false);
        TextSelectCharacter.SetActive(true);
    }
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
31.03.2022, 20:50
Ответы с готовыми решениями:

Выдает ошибку System.IndexOutOfRangeException: "Index was outside the bounds of the array." Что с этим делать?
вот код using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using...

IndexOutOfRangeException: Index was outside the bounds of the array
Делаю следующие, разбиваю массив и беру значения answ=&quot;Answer&lt;#&gt;Data&quot;; string b = answ.Split(new string { &quot;&lt;#&gt;&quot; },...

IndexOutOfRangeException: Index was outside the bounds of the array
Массив выходит за пределы не могу понять где , помогите пожалуйста! юнити ругается,говорит что ошибка на 155 строке. using...

3
566 / 363 / 208
Регистрация: 18.10.2019
Сообщений: 1,231
31.03.2022, 20:54
defoh, замени в методе ArrowRight:
Цитата Сообщение от defoh Посмотреть сообщение
if (i < AllCharacters.Length)
На:
C#
1
if (i < AllCharacters.Length - 1)
И, кстати, сразу заметил в методе ArrowLeft замени:
Цитата Сообщение от defoh Посмотреть сообщение
if (i < AllCharacters.Length)
На:
C#
1
if (i > 0)
1
1 / 1 / 0
Регистрация: 31.03.2022
Сообщений: 28
31.03.2022, 20:58  [ТС]
Спасибо,очень помогло
Не знаю что за ошибка, но когда в первый раз запускал свой код все работало
0
566 / 363 / 208
Регистрация: 18.10.2019
Сообщений: 1,231
31.03.2022, 21:04
defoh, ошибка возникает, когда ты доходишь до крайних значений массива.
AllCharacters.Length возвращает количество элементов (последний индекс + 1, т.к. индексация начинается с 0)
Поэтому, находясь на пограничном значении с концом массива и прибавляя единичку ты выходишь за пределы массива, вызывая ошибку.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
31.03.2022, 21:04
Помогаю со студенческими работами здесь

System.IndexOutOfRangeException: Index was outside the bounds of the array
System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Windows.Forms.Control.MarshaledInvoke(Control...

System.IndexOutOfRangeException Index was outside the bounds of the array
Приветствую всех. Столкнулся с проблемой System.IndexOutOfRangeException Index was outside the bounds of the array. Имеется код ...

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

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

Ошибка System.IndexOutOfRangeException: "Index was outside the bounds of the array."
В 18 строке выдает ошибку System.IndexOutOfRangeException: &quot;Index was outside the bounds of the array.&quot;. Я предполагаю, что это из за...


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

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK сделайте это, JDK, то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Перейдите по ссылке:. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru