IndexOutOfRangeException: Index was outside the bounds of the array.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScaleBgGameImg : MonoBehaviour
{
    public Camera mainCam;
    public GameObject[] Force ;
    private float srcHeight;
    private float srcWidth;
    private float DEVICE_SCREEN_ASPECT;


    // Start is called before the first frame update
    void Start()
    {
       
        srcHeight = Screen.height;
        srcWidth = Screen.width;
        DEVICE_SCREEN_ASPECT = srcWidth / srcHeight;
        mainCam.aspect = DEVICE_SCREEN_ASPECT;
        ForceALL();

    }

    private void ForceALL()
    {
        float camHeight = 60 + mainCam.orthographicSize + 2.0f;
        float camWidth = camHeight + DEVICE_SCREEN_ASPECT;

        for (byte i = 0; i <= Force.Length; i++)
        {
            SpriteRenderer _ForceRS = Force[i].GetComponent<SpriteRenderer>();
            float ForceH = _ForceRS.sprite.rect.height;
            float ForceW = _ForceRS.sprite.rect.width;
            float Force_scale_ratio_Height = camHeight / ForceH;
            float Force_scale_ratio_Whidth = camWidth / ForceW;

            Force[i].transform.localScale = new Vector3(Force_scale_ratio_Whidth, Force_scale_ratio_Height, 1);
        }
    }
}
for (byte i = 0; i < Force.Length; i++)
       // remove =

And why you use byte ?Why not int?

To reduce the memory that the system has reserved. I use no more than twenty

True. Anyway is the error gone .

it’s always an int for an array access expression.
But then convert the byte to int to get the the item from array then you are paying extra to cast to int don’t it ?

This is a quality example of “going way too far in optimization”. TBH if you’re working on a project where memory is so tightly constrained that this could possibly matter, you wouldn’t be using Unity.

2 Likes

No, I just want to keep some objects in the case of frequently being used in various screen sizes.

Thank you for your advice.