- Home /
IndexOutOfRangeException when activating a component(follow-up question)
This is a follow up question from my previous question about index's. I am receiving an array index out of range exception when I instantiate a prefab. The code successfully gives me the index but I can't seem to activate/interact with the game Objects component. I receive the IndexOutOfRangeException. I don't want the array or list to be limited to a specific count; lets say up to 10 cause I have a Gui button that when I click it. It spawns that prefab I'm trying to interact with.
Here's the Sample Code: using UnityEngine; using System.Collections;
public class IndexSample : MonoBehaviour {
//Array list for identifying indexes
//static ArrayList MovePlayer = new ArrayList();
GameObject[] PlayersObject;
int i;
//End Array list
RaycastHit hit;
public Light myLight;
public bool Selected = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
//Debug.DrawRay(ray.origin, ray.direction * 100, Color.green);
if(Physics.Raycast(ray, out hit, 100))
{
//ARRAY Index implementation
PlayersObject = GameObject.FindGameObjectsWithTag("Player");
for(i = 0; i < PlayersObject.Length;i++)
{
if(hit.collider.gameObject == PlayersObject[i].gameObject){
print (i);
}
}
//End
print ("Here is an object!");
if (hit.transform.gameObject.tag == ("Ground")){
//Debug.DrawRay(ray.origin, ray.direction * 100, Color.red);
print ("Ray has Hit the Ground");
}
else if (hit.transform.gameObject.tag == ("Player")){
Debug.DrawRay(ray.origin, ray.direction * 100, Color.blue);
if ((Input.GetMouseButtonDown(0))&&(hit.transform.gameObject.tag == "Player")){
print("You Clicked the Player!");
//GameObject[] light = GameObject.FindGameObjectsWithTag("Player");
//myLight = light[i].GetComponent<Light>();
myLight = PlayersObject[i].GetComponent<Light>();
myLight.enabled = true;
Selected = true;
}
else
{
}
}
}
}
}
Answer by robertbu · Aug 01, 2013 at 05:02 AM
The lack of correct indentation on this code makes it very difficult to read. Also it would have been very helpful if you'd pasted in the error message from the console.
Your error appears to be on line 46. On line 28, you cycle through a 'for' loop printing out your game objects. That loop terminates with 'i' is equal to PlayersObject.Length. Arrays are zero based. So the valid indices for a five element array is 0,1,2,3 & 4. So when the 'for' loop is done, 'i' is one beyond the valid indices for the array. You use this i-set-to-an-invalid-index on line 45 causing the error. Right now your 'for' loop ends on line 33. I'm guessing the code from line 35 to 47 should be inside the loop.
I already solved the error sir but thanks for the answer