I have this code that checks any objects with raycast in a grid type area, let’s say 10 x 10. The objective is to get an array filled with all enemies in the area, like:
*entitiesToGet[0].entName = “enemy one”;
entitiesToGet[0].entActualPos = Vector 3(1,0,5)*
and so on.
The code is this:
using UnityEngine;
using System.Collections;
public class CheckArea : MonoBehaviour {
[System.Serializable]
public class EntitiesInArea {
public string entName;
public Vector3 entActualPos;
}
public EntitiesInArea[] entitiesToGet;
void Start() {
entitiesToGet[0] = new EntitiesInArea();
}
void CheckArea () {
int entityNumber = 0;
for (int z = 0; z < 10; z++) {
for (int x = 0; x < 10; x++) {
RaycastHit[] hits;
hits = Physics.RaycastAll(new Vector3(x, 2, z), Vector3.down, 1f);
int i = 0;
while (i < hits.Length) {
RaycastHit hit = hits[i];
// this is to check which entity is in this cell (x and z)
if (hit.collider.gameObject.tag == "Enemies") {
entitiesToGet[entityNumber] = new EntitiesInArea();
entitiesToGet[entityNumber].entName =hit.collider.gameObject.name;
entitiesToGet[entityNumber].entActualPos = hit.transform.position;
entityNumber++;
}
//Debug.Log ("Who is here?:" + hit.collider.gameObject.name);
i++;
}
}
}
}
}
At first I was getting the “NullReferenceException: Object reference not set to an instance of an object” error, but that was fixed with the “[System.Serializable]” line (after I did some research).
Still, I’m sure something is wrong, because I keep getting the error “IndexOutOfRangeException: Array index is out of range” when trying to access the elements of the array. Obviously, when no objects with tag “Enemies” are found, the array must be empty and nothing is done. Please notice that the array will have a dynamic length, depending on how many enemies are found in the area. I think that’s not the way to access elements of a class in an array.
Please tell me what I’m doing wrong, thanks in advance.