Abdou023
Abdou023

Reputation: 1664

Check whether an array in the inspector is empty

I have a public array that should be filled in the inspector, and I want to do something if that array is empty. That array is empty in the inspector "size = 0"

public GameObject[] objects;

    void CheckArray ()
    {
        if (objects.Length < 0 ) // this doesn't work
        {
            Debug.Log("Empty!");  
        }
        else 
        {
            Debug.Log("Not Empty"); // this gets logged out
        }
    }

The above doesn't work, I tried something else but also doesn't work:

void CheckArray ()
    {
        if (objects == null ) // this doesn't work
        {
            Debug.Log("Empty!");  
        }
        else 
        {
            Debug.Log("Not Empty");  // this gets logged out
        }
    }

Upvotes: 0

Views: 1842

Answers (1)

Programmer
Programmer

Reputation: 125305

Your if statement if (objects.Length < 0 ) is wrong.

Array is usually 0 when empty. When it is 0, if (objects.Length < 0 ) will never be true because you are checking if array length is less than 0 instead of if array length is equals to 0..

That should be if (objects.Length == 0 ) or if (objects.Length <= 0 )

EDIT:

Ok this worked but it doesn't make any sense to me, because when I add an object and check for "objects[0]" it returns that object, meaning an array with 1 object in it will be indexed at 0, but at the same time a "Length" of 0 means it's empty?

There is an array size, there are elements. When I say empty, I meant not setting the size from the Editor. Since objects is a public variable, Editor will give it default value of 0. That 0 is what I meant when I say empty array.The Debug.Log(objects.Length); will output 0.

Empty array:

enter image description here

Non Empty Array:

enter image description here

In this case, Debug.Log(objects.Length); should print 3 even though that Element 1 is null or nothing is assigned to it. objects.Length will always equals to the size set in the Editor.

GameObject camera = objects[0];
GameObject someObj = objects[1]; //ELEMENT IS NULL
GameObject dLight = objects[2];

Want to check if each individual element is null?

for (int i = 0; i < objects.Length; i++)
{
    if (objects[i] == null)
    {
        Debug.Log("Empty!: " + i);
    }
    else
    {
        Debug.Log("Not Empty: " + i);
    }
}

Upvotes: 3

Related Questions