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