Common question - Check your if statements and remember that counting starts from 0
Array Index is out of range
Hello, I am currently writing my crafting script that uses UI (as you will probably see in the script). I have my for loop in AssignRecipes that is called from my main inventory script. This method takes all of the recipes that the player has learned and assigns them to buttons in the UI. X is for the recipe array and Z is for the buttons array. recipes[x] works fine throughout the method until: buttons[z].onClick.AddListener(delegate { AssignDescriptions(recipes[x]); }); When it gets here I get the IndexOutOfRangeException: Array index is out of range error. I have no idea why just here and no where else. When x in this line is replaced by 0 it works fine btw, and no, it's not a problem with the inspector array length. Crafting_Recipes is a scripts bleeding object. Script:
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class Crafting_002 : MonoBehaviour {
[Header("Scripts")]
public Inventory_001 inventory;
public Equipment_001 equipment;
[Header("Recipes")]
public Crafting_Recipes[] recipes = new Crafting_Recipes[10];
[Header("Buttons")]
public Button[] buttons = new Button[10];
[Header("Texts")]
public Text[] buttonTexts = new Text[10];
public Text itemDesc;
public Text itemRecipe;
public void AssignRecipes ()
{
int z = 0;
for (int x = 0; x < recipes.Length; x++)
{
//print(x);
print(recipes.Length);
if (recipes[x] != null && recipes[x].learned == true)
{
print(recipes[x].name);
buttons[z].gameObject.SetActive(true);
buttonTexts[z].text = recipes[x].name;
print(x);
if (x == 0)
{
buttons[z].onClick.AddListener(delegate { AssignDescriptions(recipes[x]); });
}
z++;
}
}
}
public void AssignDescriptions (Crafting_Recipes recipe)
{
itemDesc.gameObject.SetActive(true);
itemDesc.text = recipe.description;
itemRecipe.text = recipe.recipe;
}
}
This would be a good time to add some Debug.Log() output to see what is going on. $$anonymous$$y assumption is that the Length of buttons is somehow 0. Even though your code says buttons is a length of 10, I can't know further without seeing your inspector window.
I can send my inspector window tonight when I get home. I don't know why this question was closed as I have stated I know where the problem is. I know counting starts from zero, my if statements are fine, and my arrays are the right length because they are public and I have things in the arrays in the inspector. It is inside the delegate where I have the problem, if I replace the X in there with a 0 it works fine. I have many print statements in there that tell me lengths of arrays and whay x is.