E
E
Evil172019-12-05 00:19:03
Unity
Evil17, 2019-12-05 00:19:03

Error IndexOutOfRangeException: Array index is out of range, what should I do?

Good day.
I decided to write my first project in unity v5.
I wrote according to the guide, but I get the error IndexOutOfRangeException: Array index is out of range.Game.Shopbttn_addBonus (Int32 index) (at Assets/Scripts/Game.cs:27)
Here is the script:

spoiler

using System.Reflection;
using UnityEngine;
using UnityEngine.UI;

public class Game : MonoBehaviour
{
    public Text ScoreText;
    private int Score;
    private int Bonus = 1;
    [Header("Магазин")]
    public int[] ShopCosts;
    public int[] ShopBonuses;
    public Text[] ShopBttnsText;
    public GameObject Shop;

    private void Update()
    {
        ScoreText.text = Score + "$";
    }

    public void Shop_()
    {
        Shop.SetActive(!Shop.activeSelf);
    }
    public void Shopbttn_addBonus(int index)
    {
        if (Score >= ShopCosts[index])
        {
            Bonus += ShopBonuses[index];
            Score -= ShopCosts[index];
            ShopCosts[index] *= 2;
            ShopBttnsText[index].text = "КУПИТЬ УЛУЧШЕНИЕ \n" + ShopCosts[index] + "$";
        }
        else
        {
            Debug.Log("Не хватает!");
        }
    }


    public void OnClick ()
    {
        Score += Bonus; 
    }

}

Write preferably immediately a decision with an explanation, since I do not understand anything.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yuopi, 2019-12-05
@yuopi

public void Shopbttn_addBonus (int index) {
        try {
            if (Score >= ShopCosts[index]) {
                Bonus += ShopBonuses[index];
                Score -= ShopCosts[index];
                ShopCosts[index] *= 2;
                ShopBttnsText[index].text = "КУПИТЬ УЛУЧШЕНИЕ \n" + ShopCosts[index] + "$";
            } else {
                Debug.Log ("Не хватает!");
            }
        } catch (Exception e) {
            Debug.Log ($"Неверный индекс кнопки. Был передан индекс {index}, " + 
            "валидные числа индекса для массива: " + 
            $"ShopCosts - от 0 до {ShopCosts.Count - 1}" +
            $"ShopBonuses - от 0 до {ShopBonuses.Count - 1}" +
            $"ShopBttnsText - от 0 до {ShopBttnsText.Count - 1}");
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question