I have had some use of this little script, so I thought I’d share it.
When working with level designers, I have often found the need to create some more descriptive error messages than a NullReferenceException when some public inspector variable is needed before the code will work properly.
So to begin with, I had maybe 50 different class files that all started with something like:
void Awake()
{
if (winFieldBackground != null)
{
winFieldBackground.SetActiveRecursively(false);
}
else
{
log.Error("Define Win Field Background in the inspector.");
}
if (winFieldBig == null)
{
log.Error("Define Win Field Big in the inspector.");
}
if (winFieldFront != null)
{
winFieldFront.SetActiveRecursively(false);
}
else
{
log.Error("Define Win Field Front in the inspector.");
}
if (winFieldHighlighted != null)
{
winFieldHighlighted.SetActiveRecursively(false);
}
else
{
log.Error(GameConfig.CUSTOM_INSPECTOR_ERROR("WinFieldHighligted GameObject"));
}
if (winFieldActivated == null)
{
log.Error(GameConfig.CUSTOM_INSPECTOR_ERROR("WinFieldActivated Particle System"));
}
}
It could also sort of cludder the code, if I always had to make sure something wasn’t null before doing something else, just for the sake of level designers/graphic artists/whoever who was not code-savvy.
So I made a small GameObjectHelper class which among other things had this little snippet:
using UnityEngine;
using System;
using System.Reflection;
using GameLib.Logging;
namespace GameLib.UnityExtensions
{
public static class GameObjectHelper
{
public static void AssertInspectorVariables(object c)
{
FieldInfo[] fields = c.GetType().GetFields();
foreach (FieldInfo f in fields)
{
if (f.FieldType == typeof(GameObject))
{
if (f.GetValue(c).Equals(null))
{
log.Error(GameConfig.CUSTOM_INSPECTOR_ERROR(f.Name));
}
}
}
}
}
}
So I have this custom error script that gives some generic error messages, but it could just as well have been a Debug.Log()
So now, I can just write this in the beginning of my scripts:
void Awake()
{
GameObjectHelper.AssertInspectorVariables(this);
}
I don’t know if this is trivial, but it was cool to me.
Hope this can be of use.
/Kas