IndexOutOfRangeException:尝试访问GameObject数组时,数组索引超出范围?

时间:2018-07-02 19:38:49

标签: c# unity3d scope

所以我试图从用FindGameObjectsWithTag初始化的GameObject数组访问元素,但是出现以下错误

  

“ IndexOutOfRangeException:数组索引超出范围。”,

当我打印数组的长度时,我应该得到3。我该如何解决?

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 个答案:

答案 0 :(得分:5)

您可以在objects[]函数中声明局部Start变量,以隐藏字段objects。只需从objects函数

中删除start数组的声明

您可以尝试一下。

public GameObject[] objects;
void Start () {
    objects = GameObject.FindGameObjectsWithTag("isari");  
    Debug.Log (objects.Length);
}
相关问题