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 way 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
CodePudding user response:
How can I validate all variables at once
when exactly? On compile time these are most probably always gonna be null.
You could of course go for reflection and use a certain attribute - or simply use the existing one SerializeField
and only check those like e.g.
var type = GetType();
var serializedFields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Where(field => field.FieldType.IsValueType && (field.IsPublic || field.IsDefined(typeof(SerializeField)))).ToArray();
foreach (var field in serializedFields)
{
var value = field.GetValue(this);
if (value == null)
{
Debug.LogError($"{field.Name} is not referenced!");
}
}