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.
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.