

In my current project in Unity3D I wanted to create tool to watch how difficulty level changes during the game.
The idea was to set attribute to method and watch results in editor window.
Lets say we have this mathf formula to increase score speed, which depends on level difficulty.
First step is to create attribute class and set it to method.
The class is static because I don’t want to execute method on any object.
public static class MathFormula
{
[DebugWatch]
public static float GetScoreIncreasmentSpeed()
{
return Mathf.Pow((1f - GameController.difficultyLevel), 2) * GameData.scoreIncreasment;
}
}
[AttributeUsage(
AttributeTargets.Method,
AllowMultiple = true)]
public class DebugWatchAttribute : Attribute { }
When attributes are prepared we have to create unity editor window class.
This class store and get all methods with DebugWatch attribute.
The code below do the case.
public class DebugWatchWindow : EditorWindow
{
System.Reflection.MethodInfo[] methodsToWatch;
[MenuItem("Custom/Debug Watch")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(DebugWatchWindow));
}
//We use repaint in Update to avoid not refreshing if window is not focused
//Ofcourse you can slow down update frequency if methods are heavy
private void Update()
{
//Remember to resubscribe methods after add or remove methods to watch
if (methodsToWatch == null)
SubsribeMethods();
Repaint();
}
private void OnGUI()
{
if (methodsToWatch != null)
{
for (int i = 0; i & lt; methodsToWatch.Length; i++)
{
//Invoke method and show result as label field
EditorGUILayout.LabelField(methodsToWatch[i].Name, methodsToWatch[i].Invoke(null, null).ToString());
}
}
}
void SubsribeMethods()
{
methodsToWatch = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x = > x.GetTypes())
.Where(x = > x.IsClass & amp; & x.IsAbstract) // check if type is static and is class
.SelectMany(x = > x.GetMethods()) // get all methods in those classes
.Where(x = > x.GetCustomAttributes(typeof(DebugWatchAttribute), false).FirstOrDefault() != null)//with Debug Watch Attribute
.ToArray();//store methods as array to not kill fpses
}
}
Example Result
With this system we can just add attribute and watch how results change during game.
It’s usefull to balance gameplay.
There is ofcourse other methods to achieve it, just for me this one is comfortable.