Very basic code yet IndexOutOfRangeException: Index was outside the bounds of the array.

public class Button : MonoBehaviour
public Material mButton;
Renderer rend;

    // Start is called before the first frame update
    void Start()
        rend = GetComponent<Renderer>();
        rend.sharedMaterial = mButton[0];

I am getting a “Index Out of Bounds” error at the rend.sharedMaterial=mButton[0] line. It is an array of two elements. I have different materials in each of the two locations of the array. The Debug. Log accurately shows which material is in the [0] location.

Any ideas? Thanks in advance.


As you declare mButton but I dont see a value assigin code, i supose you assign it via inspector. Are you sure you defined the array and its elements? can you post a screenshot of the inspector to see it? Think that you need to assign the values for each buton script if you are doing it via inspector. there are more than 1.

By now, you can say only 1 thing is true. If error says IndexOutOfRangeException, is because index is higher than the number of elements. As you use the 0, it means the array is empty, so check why.


So someone on a another forum asked me to double-check that the error wasn’t coming from the Debug.Log line and indeed it was. When I comment out the Debug.log line, it clears the error. Thank you @tormentoarmagedoom for your assistance as well.