So I'm trying to access an element from GameObject array initialized with FindGameObjectsWithTag but I get the following error
"IndexOutOfRangeException: Array index is out of range.",
when I print the length of the array I get 3, as it should be. How do I fix it?
public class selectObject : MonoBehaviour {
// Use this for initialization
public GameObject[] objects;
void Start () {
GameObject[] objects = GameObject.FindGameObjectsWithTag("isari");
Debug.Log (objects.Length);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mouse is down");
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
Vector3 position = hitInfo.transform.gameObject.transform.position;
Quaternion rotation = hitInfo.transform.gameObject.transform.rotation;
Debug.Log("Hit " + hitInfo.transform.gameObject.name);
Object.Instantiate (objects[0], position,rotation);
Object.Destroy (hitInfo.transform.gameObject);
if (hitInfo.transform.gameObject.tag == "Construction")
{
Debug.Log ("It's working!");
} else {
Debug.Log ("nopz");
}
} else {
Debug.Log("No hit");
}
Debug.Log("Mouse is down");
}
}
}