Array index out of range Exception

Hi! Guys I am working on a project and I am changing materials of a gameobject at run time. I have made an array and stored all materials in it. On every key pressed I change the material but it is giving me the error Array index out of range exception: on line 10,18 and 26. On every point where i am changing the matterial while I can not recognize the problem. Here is my code.

using UnityEngine;
using System.Collections;
public class Materialchange : MonoBehaviour {
    public Material[] mymaterials;
    public int indexcount=0;
    public Renderer rend;
    void Start () {
        indexcount = 0;
        rend = GetComponent<Renderer> ();
        rend.material = mymaterials [indexcount];
    }
    void Update () {
        if (Input.GetKeyDown (KeyCode.RightArrow) || Input.GetKeyDown (KeyCode.Return))
      {
            if (indexcount == 0 && indexcount < 10)
            {
                indexcount ++;
                rend.material = mymaterials[indexcount];
            }
        }
        else if (Input.GetKeyDown (KeyCode.LeftArrow) || Input.GetKeyDown (KeyCode.Backspace))
        {
            if (indexcount > 0 && indexcount < 10)
            {
                indexcount --;
                rend.material = mymaterials[indexcount];
            }
        }
    }
}

Help is appreciated. Sorry for bad english. Thanks in advance.

The problem is when indexcount is greater than mymaterials.Length - 1

Thanks a lot @bart_the_13th . Thanks again buddy I was stuck in this issue from last 2 days and you solved my problem. :slight_smile:

Aye, no problem mate…
just a bit of tips, try to log variables in the error line using Debug.Log() or print()…

1 Like

I will next time bro… THanks for tip. :slight_smile: