my script only instantiates the last object in the array

Making a script where the mouse wheel determines what build object preview will be instantiated but only works till i scroll using the mouse wheel and setting the “selected build” variable to 7 and its calling the else statement below 7 for some reason

public class BuildManager : MonoBehaviour {

    

    public GameObject[] buildObjectPreviews;
    public BuildSystem system;
    public int selectedBuild = 0;
    public int previousSelectedBuild;
    public int[] oilCost;
    public int[] metalCost;

    private void Start()
    {
        system = GetComponent<BuildSystem>();
        //SelectBuild();
        
    }

    private void SelectBuild()
    {
        
        for (int i = 0; i < buildObjectPreviews.Length - 1; i++)
        {
            if (i == selectedBuild)
            {
                
                Debug.Log(i);
                system.NewBuild(buildObjectPreviews[selectedBuild], oilCost[selectedBuild], metalCost[selectedBuild]);
            }
            else  {
                Debug.Log("test");
                system.CancelBuild();
            }
                
           
                

        }

    }

    private void Update()
    {
        previousSelectedBuild = selectedBuild;
        if (Input.GetAxis("Mouse ScrollWheel") < 0f)
        {
            if (selectedBuild <= buildObjectPreviews.Length - 1)
                selectedBuild = 0;
            else
                selectedBuild--;

        }

        if (Input.GetAxis("Mouse ScrollWheel") > 0f) {
            if (selectedBuild >= buildObjectPreviews.Length - 1)
                selectedBuild = 0;
            else
                selectedBuild++;

        }

        if (previousSelectedBuild != selectedBuild) {

            SelectBuild();

        }
        
    }

Hey,
the bug is twofold.

In section 45. where you check selectedBuild <= buildPrevious.Length -1;
This should be selectedBuild < 0; instead.

And also in section 55. if(selectedBuild >= buildObjectPreviews.Length -1)
here selectedBuild should be set to buildObjectPreviews.Length -1 instead of 0.

There are also other improvements that can be made to your code:
For example, you do not need the for-loop inside SelectBuild(). Since you don’t need the i-variable, you can just use selectedBuild instead.
Also SelectBuild should be renamed to PreviewBuild or the like to better communicate what is happening here.

Hope it helps. Cheers, IronBytes.