-1
\$\begingroup\$

I have a problem that, when exceeding the maximum or minimum texture in the matrix, is giving this error, what can I do?

IndexOutOfRangeException: Array index is out of range.

    public void previous(){
    currentTexture--;
    shouldChange = false;
}

public void next()
{
    currentTexture++;
    shouldChange = true;
}

void Update()
{
    if (texture.Length == 2)
        return;
    if (texture.Length == 0)
        return;
        {
            for (int i = 0; i < arrays.Length; i++)
                arrays[i].material.mainTexture = texture[currentTexture];
        }
\$\endgroup\$
1
\$\begingroup\$

An IndexOutOfRange exception is an exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds (index < 0 or >= length of the array)

You need to make sure your currentTexture does not go outside those bounds. Here is a solution to make the currentTexture loop (of value was supposed to go below 0, it will take the value length - 1, if the value was supposed to go over length - 1, it will have a value of 0)

public void previous()
{
    currentTexture = (currentTexture + texture.Length - 1) % texture.Length;
    shouldChange = false;
    SetTexture();
}

public void next()
{
    currentTexture = (currentTexture + 1) % texture.Length;
    shouldChange = true;
    SetTexture();
}

private void SetTexture()
{
    if (texture.Length == 2 || texture.Length == 0)
        return;
    for (int i = 0; i < arrays.Length; i++)
        arrays[i].material.mainTexture = texture[currentTexture];
}

/*
// Remove this unnecessary Update
void Update()
{
    if (texture.Length == 2)
        return;
    if (texture.Length == 0)
        return;

    for (int i = 0; i < arrays.Length; i++)
        arrays[i].material.mainTexture = texture[currentTexture];
}
*/
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.