Created
November 27, 2019 05:51
-
-
Save BeautyfullCastle/95105238a989c581bcb6204b563e9894 to your computer and use it in GitHub Desktop.
Null check member fields using SerializeField attribute.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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