Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom Validator in Unity

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading