The question is answered, right answer was accepted
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()
{
Debug.Log(mButton[0]);
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.
Answer by Siggytron · Feb 18, 2020 at 10:17 PM
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.
This probably means you have two copies of button in the scene. In hierarchy search fro Button it will show you all the GameObjects with that script assigned. Then you can make sure all the materials are assigned.
@$$anonymous$$ensct Right that was my first thought too, at StackOverflow where the question was crossposted.
Answer by tormentoarmagedoom · Feb 18, 2020 at 06:48 PM
Hello.
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.
Bye!
You're right that I am assigning it via the inspector. Here is the screenshot of my inspector. (I changed the script name to 'Next').
(For some reason, the upload function keeps giving me a parsing error) I'll try to describe my inspector then.
$$anonymous$$ Button
Size 2
Element 0 $$anonymous$$aterial named 'Aqua'
Element 1 $$anonymous$$aterial named 'Pink'
Also, how would I assign materials to the array before I give the instruction to get the renderer? I tried assigning arbitrary integers when I declare the array, but Unity won't let me set up the array with integers and then have it switch over to holding materials.
Thanks.
Follow this Question
Related Questions
IndexOutOfRangeException: Array index is out of range. on "frequency = frequencies[thisFreq];" 0 Answers
C# List index confusion using Mathf.Clamp 1 Answer
Error: IndexOutOfRange: call for index 0 in an array with length 1(+) 1 Answer
Array of Arrays 3 Answers
Array cannot read Greek characters 1 Answer