본문 바로가기
Unity/Unity 관련 오류 해결

ArgumentOutOfRangeException 에러 원인과 해결

by 민트코코넛 2021. 5. 24.
728x90
반응형

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

 

생성된 리스트의 크기를 초과한 인덱스의 크기 때문에 발생하는 문제점.

 

해당 이슈가 발생했었던 부분은 다음과 같다.

private void DolphinCenterSpawn()
    {
        Vector3 screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
        List<ARRaycastHit> hits = new List<ARRaycastHit>();
        aRRaycastManager.Raycast(screenCenter, hits, TrackableType.All);
        
        // 문제 발생 부분
        Pose placementPose = hits[0].pose;
        placementPose.position = new Vector3(1.5f, 3f, 20f);
        placementPose.rotation = Quaternion.Euler(0, 35, 0);
        //
        
        if (hits.Count > 0)
        {
            DolphinModel.SetActive(true);
            DolphinModel.transform.SetPositionAndRotation(placementPose.position, placementPose.rotation);
        }
    }

AR 카메라에서 터치가 된 부분에 오브젝트를 불러오기 위한 코드인데, 이때, 레이가 닿는 hits의 배열 크기에 대한 설정 위치를 잘못 설정하는 바람에 해당 이슈가 발생했다.

 

원인 파악 후, 해결을 위하여 이동한 코드 위치 모습은 다음과 같다

private void DolphinCenterSpawn()
    {
        Vector3 screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
        List<ARRaycastHit> hits = new List<ARRaycastHit>();
        aRRaycastManager.Raycast(screenCenter, hits, TrackableType.All);

        if (hits.Count > 0)
        {
            //
            Pose placementPose = hits[0].pose;
            placementPose.position = new Vector3(1.5f, 3f, 20f);
            placementPose.rotation = Quaternion.Euler(0, 35, 0);
            //
            DolphinModel.SetActive(true);
            DolphinModel.transform.SetPositionAndRotation(placementPose.position, placementPose.rotation);
        }
    }

위처럼 바깥에 있던, hits[] 에 대한 부분을 if문 내부로 이동하니 해당 이슈가 해결되었다.

728x90