IndexOutOfRangeException: Index was outside the bounds of the array. :0

when i hit a key one time to switch state it works but secund time i get IndexOutOfRangeException: Index was outside the bounds of the array. anyone knows why​:hugs::roll_eyes:
code:

AdventureGame.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AdventureGame : MonoBehaviour
{

    public Text textComponemt;
    public State startingState;

     
    
    
    State state;
    
    
    
// Start is called before the first frame update
    void Start()
    {
        state = startingState;
        textComponemt.text = state.GetStateStory();
    }

// Update is called once per frame
    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];
        }
        textComponemt.text = state.GetStateStory();

    }
} 

state.cs

type or pasusing System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject
{
    [TextArea(19, 14)] public string storyText;
    [SerializeField] State[] nextStates;
    public string GetStateStory()
    {
        return storyText;
    }


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

    
}

Hi,

Welcome to our community! :slight_smile:

ArgumentOutOfRange / IndexOutOfRange exception means that the code tried to access a non-existent index in an array, List or another collection. The first index in an array and List is 0, hence the last index is the length minus 1. For example, if the array has got a length of 2, and the code tries to access index 2, you will get this error message because there are only two “slots” in the array: at index 0 and at index 1.

This is a known problem in our game, which Rick fixes in lecture “For Loops”.


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms