Events - AddUObject/RemoveUObject Crashing

UPDATE: The crash definitely happens after 40+ seconds of clicking around. Never happens before. So something is being garbage collected in Invocation List of the Event Delegate?

I am working on an RTS style game that depends heavily on Events.

  • Player selects the Unit.
  • Unit gets subscribed to MyEvent using AddUObject
  • Player unselects the Unit.
  • Unit gets removed from MyEvent using RemoveUObject

Obviously, the above subscribing / unsubscribing happens quite frequently as the Player keeps clicking around the Units in the game.

Here is the pseudo-code snippet:



if (Selected) {
(MyPlayerController->MyEvent).AddUObject(MyUnit, &MyUnitClass::ReactToSelect);
} else {
(MyPlayerController->MyEvent).RemoveUObject(MyUnit, &MyUnitClass::ReactToSelect);
}


This runs well. I can select/unselect Units. I see they are correctly subscribed/unsubscribed. And they perform the correct behavior when MyPlayerController broadcasts MyEvent.

But randomly, the game crashes at **AddUObject **or **RemoveUObject **. I could see absolutely no reproducable pattern. It just sometimes crashes while I am clicking around. I am doing all the null-checks, they are fine.

I even used


IsBoundToObject()

to confirm the Unit is actually subscribed to MyEvent before calling **RemoveUObject ** on it. When I do that, now the game randomly crashes at IsBoundToObject(). I am really stumped, any help or insight would be appreciated. Here is stacktrace:



!Id:639d3519fc5c4c3b483eb4a2181407cd
Access violation - code c0000005 (first/second chance not available)
Fatal error!
UE4Editor_Pawn1!FMulticastDelegateBase<FWeakObjectPtr>::IsBoundToObject() + 20 bytes [c:\program files\unreal engine\4.3\engine\source\runtime\core\public\delegates\multicastdelegatebase.h:50]

UE4Editor_Pawn1!AMyUnit::SetSelected() + 272 bytes [c:\users\profohara\documents\ue4\pawn1\source\pawn1\myunit.cpp:126]

UE4Editor_Pawn1!TBaseUObjectMethodDelegateInstance_OneParam<AFred,void,int>::ExecuteIfSafe() + 197 bytes [c:\program files\unreal engine\4.3\engine\source\runtime\core\public\delegates\delegateinstancesimpl.inl:532]

UE4Editor_Pawn1!TBaseMulticastDelegate_OneParam<void,int>::Broadcast() + 130 bytes [c:\program files\unreal engine\4.3\engine\source\runtime\core\public\delegates\delegatesignatureimpl.inl:1852]
UE4Editor_Pawn1!AJackPlayerController::ProcessLMC() + 181 bytes [c:\users\profohara\documents\ue4\pawn1\source\pawn1\myplayercontroller.cpp:131]

UE4Editor_Pawn1!AJackPlayerController::PlayerTick() + 32 bytes [c:\users\profohara\documents\ue4\pawn1\source\pawn1\myplayercontroller.cpp:96]

1 Like