Answer the question
In order to leave comments, you need to log in
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:
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;
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question