- Home /
Unbound Objects Are Not Null?
I have a question concerning Unity's automatic serialization. At what point in an object's lifetime are the object's serializable fields set to the values from the inspector? Could you give me any more detail on how this works or any links for further reading please?
Also, I'm trying to detect what objects are unbound at run-time, I have an issue with the following code. I have null fields tagged with SerializeField, the code lists them fine and reports that the value is null when ToString is invoked, however the direct == null check fails. This means that for null variables, the second Warning gets shown rather than the first. If I use the same direct check with the variable name (without reflection) the check works and true is returned as it should be, but GetValue seems to be returning something which is not null but returns "null" if ToString is called. Any ideas on this one?
// Scan fields and error if any are unbound
try
{
Type type = this.GetType();
FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
for (int i = 0; i < fields.Length; i++)
{
// Is Field Tagged With SerializeField?
if (fields[i].GetCustomAttributes(typeof(SerializeField), false).Length > 0)
{
Debug.Log(fields[i].Name + " Value: " + fields[i].GetValue(this) + " " + fields[i].GetCustomAttributes(typeof(SerializeField), false).ToString().Length);
object value = fields[i].GetValue(this);
if (value == null)
{
Debug.LogWarning("Null(Method 1) field detected. Name: " + fields[i].Name);
}
else if (value.ToString() == "null")
{
Debug.LogWarning("Null(Method 2) field detected. Name: " + fields[i].Name);
}
}
}
}
catch (Exception e)
{
Debug.LogError(e);
}