Professional Documents
Culture Documents
Unity Field Validation: Open Snippit
Unity Field Validation: Open Snippit
Unity Field Validation: Open Snippit
Open Snippit
The Problem
That works...but I don't want to have scripts doing work at start, that could be
done at edit time easily enough and save performance.
[RequireComponent(typeof(Player))]
class World : MonoBehaviour
{
[SerializeField]
Player _player;
}
That will enforce it... but it means it HAS to be on this object and gets
annoying removing components because if a dependency chain.
What I Want
I want to ensure that I didn't forget to drag it in the inspector, but isn't a lot of
work to either write or to maintain.
[RequireComponent(typeof(Player))]
class World : MonoBehaviour
{
[SerializeField]
Player _player;
void Awake()
{
if(_player == null) Debug.LogError("Player cannot be null!");
}
That does what I want, but is a lot of messy code to add, especially since I
need to write one of those for every object.
void Awake()
{
_player.RequiredBy(this);
}
This looks a lot nicer but I have to remember to add a line for every single
required field. Seeing as I do this a lot, the end result starts to look pretty
heavy:
void Awake()
{
_player.RequiredBy(this);
_shop.RequiredBy(this);
_wallet.RequiredBy(this);
}
}
Cleaning the Syntax
So what if we take a queue from the [SerializedField] and make our own
attribute:
[AttributeUsage(AttributeTargets.Field)]
public class RequiredAttribute : Attribute { }
So now with the attribute we can simplify the check of what is required:
}
}
}
So now instead of having to write a new validation line for each field we can
search for each [Required] attribute and apply it to all of them, so now the
code is a lot cleaner..
this is a lot better, one line per script to validate all the fields!
... but what if we forget to write that line? we can do better:
#if UNITY_EDITOR
public class CheckMissingFields
{
[RuntimeInitializeOnLoadMethod]
static void TryValidate()
{
foreach (var behaviour in Object.FindObjectsOfType<MonoBehaviour>())
behaviour.Validate();
}
}
#endif
Now we can ask unity to automatically validate all the fields if we try to load
the project!
The Final Result