State transition with events causes absurd memory allocations

I’m using VS to build AI, and basically I have it so all the main stuff is done in C#, while the flow is handled by visual scripting state machines. This means there is virtually zero code in the state machines, just a few function calls and events, which link states like “Idle”, “Caution” etc together.

I assumed this would be a fairly performant way to handle it since I would avoid most of the reflection overhead. But I guess I was wrong. When I turn on deep profiling I can see that when a state is entered, it seems to initialize all of the events by doing all sorts of boxing, then adds them to new hashsets. It doesn’t seem to cache any of this whatsoever since the memory is allocated every time it happens. When I have many AIs active, this means suddenly 5mb+ garbage is generated when they all lock-on to the player.

Am I missing something or is it just supposed to be this inefficient?

I use EventBus.Trigger(string, gameObject, params);
Would using some other method be faster?

Update for anyone with the same issue. I mostly solved this problem by registering empty event handlers on gameobject creation. In my case it reduces GC by over 90%.

private Action<Vector3> empty = _ => { };
private EventHook canReachTargetEmptyEvent;
private EventHook completePathEmptyEvent;
private EventHook partialPathEmptyEvent;

protected virtual void RegisterEventsWorkaround()
{
    canReachTargetEmptyEvent = new EventHook(AIEventNames.OnCanReachTarget, gameObject);
    completePathEmptyEvent = new EventHook(AIEventNames.OnCompletePathToNavigationGoal, gameObject);
    partialPathEmptyEvent = new EventHook(AIEventNames.OnPartialPathToNavigationGoal, gameObject);

    EventBus.Register(canReachTargetEmptyEvent, empty);
    EventBus.Register(completePathEmptyEvent, empty);
    EventBus.Register(partialPathEmptyEvent, empty);
}

Make sure to unregister the handlers when needed (for example when the gameobject is disabled).

protected virtual void UnregisterEventsWorkaround()
{
    EventBus.Unregister(canReachTargetEmptyEvent, empty);
    EventBus.Unregister(completePathEmptyEvent, empty);
    EventBus.Unregister(partialPathEmptyEvent, empty);
}
1 Like