1

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");
        } 
    }
}

1 Answer 1

5

You declare a local objects[] variable in the Start function hiding the field objects. just remove the declaration of objects array from start function

You can try this.

public GameObject[] objects;
void Start () {
    objects = GameObject.FindGameObjectsWithTag("isari");  
    Debug.Log (objects.Length);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.