Hey I have a simple class UiManager I wanna validate all variables so they should not be null
[SerializeField] private SceneLoaderManager.SceneName gamePlaySceneName;
[SerializeField] private TextMeshProUGUI coinCountUI;
[SerializeField] private TextMeshProUGUI energyCountUI;
for now, I have only 3 variables but in the future, It can be more than 1000 I will probably validate them by checking for null but it's a lot of work to do
if (coinCountUi == null) Debug.Log ("you may forget to assign `CoinCountUi` ");
How can I validate all variables at once and throw some kind of message to the user?
I have an idea to do this but don't know how to execute it like [WarnOnNull] [SerializeField] private TextMeshProUGUI energyCountUI; please guide me how I can create Attribute like this which can validate those stuff
Part2:
namespace Randoms.Reflection
{
[AttributeUsage (AttributeTargets.All)]
public class WarnOnNullAttribute : Attribute {}
public static class TypeChecker
{
public static void WarnOnNull (this MonoBehaviour other)
{
Type type = other.GetType ();
BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.FlattenHierarchy;
FieldInfo[] fieldInfos = type
.GetFields (bindingFlags)
.Where (_ => _.IsDefined (typeof (WarnOnNullAttribute),true))
.ToArray();
foreach (FieldInfo info in fieldInfos)
{
var val = info.GetValue (other);
if (val == null)
Debug.LogWarning($"{info.Name} is not referenced!");
}
}
}
}
After
DerHugoanswer I have this code so far this code is working but still I have to write one addition line.
private void Awake ()
{
this.WarnOnNull ();
}
how I can make this work only using attributes something like this
[WarnOnNull] [SerializeField] private TextMeshProUGUI energyCountUI;