- Home /
Function like string.IsNullOrEmpty(var) but for arrays
Hi, I need to check if an array is null
Here's the context, and what I tried so far :
[OptionalField(VersionAdded = 2)] public float[] var = new float[3];
[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
if (var.Length == 0) var = new float[3];
}
I'm getting this error if I use this script :
NullReferenceException: Object reference not set to an instance of an object
Comment
Best Answer
Answer by Bunny83 · Sep 30, 2018 at 08:22 PM
The static "IsNullOrEmpty" method literally is just defined as
public static bool IsNullOrEmpty(string value)
{
return value == null || value.Length == 0;
}
insice the System.String class. There is nothing like this for arrays. You could create one yourself but it would be simpler to just do the checks yourself.
void OnDeserialized(StreamingContext context)
{
if (var== null || var.Length == 0)
var = new float[3];
}
Though the default value for an array is just null when it's not already serialized (by the BinaryFormatter).
Your answer
![](https://koobas.hobune.stream/wayback/20220612175527im_/https://answers.unity.com/themes/thub/images/avi.jpg)