Array index is out of range

I’m trying to display the correct message depending on what is clicked.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ConversationNPC : MonoBehaviour {

    public GameObject[] convNPC;
    public Text[] convText;

    private int i;

    void Start()
    {
        for (i = 0; i < convText.Length; i++) {
            convText [i].enabled = false;
        }
    }

    void Update()
    {
        if (Input.GetMouseButton (0)) {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit)) {
                for (i = 0; i < convNPC.Length; i++) {
                    Debug.Log (i);
                    if (hit.collider.tag == convNPC [i].tag)
                        break;
                }
                if (convText [i].enabled == false)
                    convText [i].enabled = true;
            }
        }
    }

}

It displays the correct text, but also an error message pops multiple times saying “Array index is out of range” (line 30).
The size of the array is 1 and I checked the value of ‘i’ and it’s 0 like it should be.

Is that the only ConversationNPC in the scene?

The length of convNPC is obviously greater than the length of convText.

That is a pretty funky statement you have there! There probably is a difference between the length of convNCP’s length and convText’s length.

This makes much more sense:

for (int i = 0; i < convNPC.Length; i++) {
  convText[i].enabled =  hit.collider.tag == convNPC [i].tag;
}

Oh, wait, I see it now. @ , what do you think this prints:

void Start() {
    int i;
    for (i = 0; i < 5; i++) {
          
    }
    Debug.Log(i);
}

It’ll print “5”, as i++ is done before the i < 5 check. So when you leave the loop, i is outside the bounds of the array you were looping through. The same thing happens here:

for (i = 0; i < convNPC.Length; i++) {
    Debug.Log (i);
    if (hit.collider.tag == convNPC [i].tag)
        break;
}
if (convText [i].enabled == false)
    convText [i].enabled = true;

if convNPC and convText are both 1 long, i will be 1 when the for-loop is done, and will be out of bounds of convText.

1 Like

Both arrays have the same length.

Thank you, I forgot to do -1.