- Home /
The question is answered, right answer was accepted
C# array index is out of range but shouldn't be, right?
I normally don't come on here for small problems like this but I've been looking at my screen for a good hour now and i'm stumped.
Basically I have 2 arrays
Array #1 contains 4 buttons so it's length is 4 Array #2 contains 4 "Actions" a class I created it's length is also 4 then.
Values are set in the inspector so should not be returning the way they are the line in question is the one that add's the listener
void QueneActions()
{
for(int i = 0; i < phrase.actions.Length; i++)
{
choices[i].GetComponentInChildren<Text>().text = phrase.actions[i].actionText;
choices[i].onClick.RemoveAllListeners();
choices[i].onClick.AddListener(() => ButtonPress(phrase.actions[i].effectText)); //returns with error array index out of range
Debug.Log("B: " + choices[i].name); //Returns without error
Debug.Log("A: " + phrase.actions[i].actionText); //Returns without error
}
}
Answer by LeeroyLin · Jun 22, 2018 at 04:35 AM
Maybe you can try this:
void QueneActions()
{
for(int i = 0; i < phrase.actions.Length; i++) //Length = 4 so i = 0, 1, 2, 3
{
int t = i;
choices[i].GetComponentInChildren<Text>().text = phrase.actions[i].actionText;
choices[i].onClick.RemoveAllListeners();
choices[i].onClick.AddListener(delegate {ButtonPress(phrase.actions[t].effectText);});
}
}
Literally just found it on another answer and was about to post that, but you beat me to it, that did it apparently delegates don't like references vs values very picky about that lol.
I also had this problem before(long long ago), and I find this way to solve it. It's too long so I'm not sure. XD
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity c# indexoutofrangeexception: array index is out of range 1 Answer
Auto-targetting script not working 0 Answers
create waypoints with an array without using "Tags" 0 Answers