Can't switch states



I can’t switch states, and instead I get IndexOutOfRange Exception. My code is the same as the video. Can someone help me please?


I am not pretty sure but i think later in the course it will be explained. I have different code now becouse I finished this section, if in the end you’ll still have a problem write post then again :slight_smile:


The exception is due to the fact that the code in the video uses conditions for up to 3 states (the if and 2 if else conditions) but we only set 2 states in unity (Room 1 and Room 2). This should be fixed or updated.

Or do you get the IndexOutOfRange Exception on any key pressed? If so take a look if your GetNextStates() method properly returns the array as expected:

public State[] GetNextStates() {
        return this.nextStates;


@Sharpin Thanks for the reply. I’ll do post again if I have problems with the code


@Vegaaaa The IndexOutOfRange exception happens only when I press 1-3 keys, that’s when I press one of those (1, 2, or 3). I don’t see the updated version. How can I fix my code. I think is something with the array index being one less than the keys pressed?


Here you have my code, but it’s after finishing the section… Remeber that .Length returns number of all pieces eg. 3 while indexes are 0-2. I recommend finish this section first to understand the code :slight_smile:



@Sharpin Thanks for the code. At least I have whatever the case. I’ll wait till the end of the section and see what happens. I appreciate that.