- Home /
How do I fix this null problem?
I am making a simple inventory and im trying to make it not do anything if the array is empty, but when it looks to see if it is null it says that it cant check because it is null. How do I fix this?.
here's part of the script
public GameObject[] Slots;
void OnGUI()
{
GUI.skin.font = font;
int offset = 0;
for (int x = 0; x <= 30; x++) {
if(Slots[x]!= null){
if (GUI.Button (new Rect (10 + offset, 140, 60, 60), Slots[1].name))
{
Debug.Log(x);
}
offset += 65;
}
}
here is the error
IndexOutOfRangeException: Array index is out of range.
ObjectHolder.OnGUI () (at Assets/Scripts/ObjectHolder.cs:37)
Answer by Habitablaba · Oct 16, 2014 at 10:45 PM
Wups. I got cocky and solved the wrong problem. Check this part out:
for (int x = 0; x <= 30; x++)
There are two things here. One is mildly alarming, and the other is your problem.
First, don't count to x<=30
, count to x < 30
. This is where you're seeing your problem. If your array is 30 big, the last valid index is 29 (since arrays are 0 based).
The mildly alarming part is that you have 30 hard coded in here. Instead, you should use the .Length of your array. This way, if your array changes size later, you won't have to change your code.
Try:
for (int x = 0; x < Slots.Length; x++)
Also, you are assu$$anonymous$$g there is more than one entry into the array on line 10 when you do Slots[1] (again because the first index is 0, not 1).
alright im going to see if this work after im done with dinner lol but I thumbed it up for the help :)
Your answer
Follow this Question
Related Questions
Is there any easy way to keep buttons inside of box? (c#) 1 Answer
Inventory Cursor Location 1 Answer
Multiple Cars not working 1 Answer