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()
		{ = 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))
				offset += 65;

here is the error

IndexOutOfRangeException: Array index is out of range.
ObjectHolder.OnGUI () (at Assets/Scripts/ObjectHolder.cs:37)

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.


for (int x = 0; x < Slots.Length; x++)