检查检查器中的数组是否为空 [英] Check whether an array in the inspector is empty

查看:71
本文介绍了检查检查器中的数组是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个公共数组,应该在检查器中填充该数组,如果该数组为空,我想做些事情.该数组在检查器大小= 0"中为空

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
        }
    }

推荐答案

您的if语句 if(objects.Length< 0)错误.

数组为空时通常为 0 .当它为 0 时, if(objects.Length< 0)永远不会为真,因为您正在检查数组长度是否小于 0 而不是如果数组长度等于 0 ..

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..

应为 if(objects.Length == 0) if(objects.Length == 0)

好吧,这行得通,但是对我来说没有任何意义,因为当我添加时一个对象并检查"objects [0]",它将返回该对象,这意味着包含1个对象的数组的索引将为0,但索引相同时间长度"为0表示它为空?

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?

有一个数组大小,有元素.当我说为空时,我的意思是不要在编辑器中设置尺寸.由于 objects 是公共变量,因此Editor将为其赋予默认值 0 .那个 0 是我说空数组时的意思. Debug.Log(objects.Length); 将输出 0 .

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.

空数组:

非空数组:

在这种情况下,即使 Element 1 null ,否则 Debug.Log(objects.Length); 应该打印3.分配给它. objects.Length 将始终等于编辑器中设置的大小.

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);
    }
}

这篇关于检查检查器中的数组是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆