Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BeautyfullCastle/95105238a989c581bcb6204b563e9894 to your computer and use it in GitHub Desktop.
Save BeautyfullCastle/95105238a989c581bcb6204b563e9894 to your computer and use it in GitHub Desktop.
Null check member fields using SerializeField attribute.
using UnityEngine;
using System.Reflection;
using System;
public static class UnityEditorExtension
{
public static void AssertCheckNullWithSerializeFields(this MonoBehaviour behaviour)
{
if (Application.isEditor == false)
{
return;
}
FieldInfo[] fieldInfos = behaviour.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo fieldInfo in fieldInfos)
{
SerializeField serializeField = null;
try
{
serializeField = fieldInfo.GetCustomAttribute<SerializeField>(true);
}
catch (Exception _)
{
continue;
}
if (serializeField != null)
{
var value = fieldInfo.GetValue(behaviour);
behaviour.Assert(value.IsNotNull(), String.Format("{0} is null.", fieldInfo));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment