IndexOutOfRangeException: AdventureGame.cs nextStates

Hi,

I’m having an issue with the AdventureGame.cs to get the next state from keyboard input. My code is like this:

   void Update()
    {
        ManageState();
    }

    private void ManageState()
    {
        var nextStates = state.GetNextStates();

        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            state = nextStates[0];
        }
        else if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            state = nextStates[1];
        }
        else if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            state = nextStates[2];
        }
        textComponent.text = state.GetStateStory();
    }

And GetNextStates is defined in State.cs as:

    public State[] GetNextStates()
    {
        return nextStates;
    }

but when I run this on Unity and press the alphanumeric 1 key, I’m always getting the same error saying that the index is out of bounds.

IndexOutOfRangeException: Index was outside the bounds of the array.
AdventureGame.ManageState () (at Assets/AdventureGame.cs:54)
AdventureGame.Update () (at Assets/AdventureGame.cs:45)

Indeed, when I do Debug.Log(nextStates.Length); the value is always 0, so it seems the array is not being created properly.

How to solve this issue?
Many thanks,
Martim

Hi Martin,

First of all, good job on narrowing down the problem.

Check your scriptable State objects. Do all of them have State objects in their array?

Hi Nina,

many thanks for your help. I’m on lecture 27 so there should not be many scriptable objects. The only one is in State.cs:

[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject {

    [TextArea(14, 10)] [SerializeField] string storyText;
    [SerializeField] State[] nextStates;

    public string GetStateStory() {
        return storyText;
    }

    public State[] GetNextStates() {
        return nextStates;
    }
}

I’m very new on Unity and C# scripting, what do you mean by " all of them have State objects in their array"?

Haven’t you created story parts in your Assets folder yet? I meant “Room 1”, “Room 2”, etc. which were created from your State object. I meant scriptable objects in Unity. What you showed is a C# class inheriting from ScriptableObject, which is a class in the Unity namespace. I know, it sounds a bit confusing but if you regard Unity and C# as two different things, a lot will become easier to grasp.

What do you have in your Assets folder? Click on all scriptable objects there, not on your State script.

This topic was automatically closed after 14 days. New replies are no longer allowed.

Privacy & Terms