Skip to content

Instantly share code, notes, and snippets.

@Deadcows
Created July 17, 2024 11:23
Show Gist options
  • Save Deadcows/0f12391d88924a0e5648d6ec27153b24 to your computer and use it in GitHub Desktop.
Save Deadcows/0f12391d88924a0e5648d6ec27153b24 to your computer and use it in GitHub Desktop.
BehaviourDesigner – Manual Error Checking for Custom Tasks
public class CustomTaskExample : Action, ITaskWithErrorCheck
{
public bool ShowError = true;
#if UNITY_EDITOR
public CustomTaskExample() => this.RegisterErrorCheck();
public bool AnyErrorInTask() => ShowError;
#endif
}
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
public interface ITaskWithErrorCheck
{
#if UNITY_EDITOR
bool AnyErrorInTask();
NodeData NodeData { get; }
#endif
}
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using UnityEditor;
namespace Gameplay.Actions
{
[InitializeOnLoad]
public static class TaskErrorCheck
{
private static readonly List<WeakReference<ITaskWithErrorCheck>> Tasks = new();
static TaskErrorCheck()
{
EditorApplication.update += CheckTasks;
void CheckTasks()
{
for (int i = 0; i < Tasks.Count; i++)
{
var taskReference = Tasks[i];
if (!taskReference.TryGetTarget(out var task))
{
Tasks.RemoveAt(i);
continue;
}
if (task.NodeData?.NodeDesigner == null) continue;
((BehaviorDesigner.Editor.NodeDesigner)task.NodeData.NodeDesigner).HasError = task.AnyErrorInTask();
}
}
}
public static void RegisterErrorCheck(this ITaskWithErrorCheck task)
{
Tasks.Add(new WeakReference<ITaskWithErrorCheck>(task, false));
}
}
}
#endif
@Deadcows
Copy link
Author

Error checking in BehaviourDesigner is not very flexible. For instance, if you want to display a custom serialized class and want the error to appear if one of its fields is null, or make a custom type with a validation more complex than mere null ref check - [RequiredField] and [SharedRequired] wouldn't help you. With this, you can create custom error checks easily, to quickly identify troublesome places in the tree:

2024-07-17_14-38-59

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment