Array index out of range error with onClick.AddListener(delegate)
I had a question that was, in my eyes, wrongly closed. I found a workaround for my script after my question was closed. I just created a holder method to transfer my scriptable object to the delegate. I am pretty sure that delegates cant take in array values with int variables saying which one. If this is a bad place to show my solution than someone please tell me where. My original question follows with a comment where I changed the code. {
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);
Crafting_Recipes holderRecipe = recipes[x]; //added as a transfer
buttons[z].onClick.AddListener(delegate { AssignDescriptions(holderRecipe); }); //changed holder recipe from recipes[x]
z++;
}
}
}
public void AssignDescriptions (Crafting_Recipes recipe)
{
itemDesc.gameObject.SetActive(true);
itemDesc.text = recipe.description;
itemRecipe.text = recipe.recipe;
}
}
Answer by Rosh7 · Feb 22, 2018 at 01:07 AM
I have my work around in the question area. If anyone has an actual answer for this please feel free to reply.
Your answer
Follow this Question
Related Questions
[WebGL 2.0] Texture2DArray support? 1 Answer
object.activeSelf and object.activeInheirarchy Both not working 0 Answers
Get all Children of an Object with a certain component 0 Answers
Unity Networking Prefab cant load scene assets 0 Answers
IndexOutOfRangeException: Array index is out of range problem 2 Answers