[C#] Passing parameters in TriggerEvent cannot be obtained on EventHandler as it causes an error

Passing parameters when calling TriggerEvent cannot be catched by EventHandler as I recieve an error of invalid arguments.
What am I missing?

TriggerEvent

TriggerEvent("playerConnectSuccessful", player);

EventHandler

[EventHandler("playerConnectSuccessful")]
private async void HandlePlayerConnected([FromSource] Player player)
{
    Debug.WriteLine($"Player {player.Name} has connected.");
}

Could you send a screenshot of the error?

Since you are manually passing the argument, you don’t need [FromSource], so try removing that. You would use [FromSource] if the event was sent from a client, to figure out which client sent the event.

1 Like

Thanks for the reply, and for letting me know about the [FromSource] :slight_smile:

I’ve removed it, yet I get the same issue.

Unhandled exception: System.ArgumentException: method arguments are incompatible
[script:main] at System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument,
System.Reflection.MethodInfo method, System.Boolean throwOnBindFailure, System.Boolean allowClosed) [0x002e3] in <fbc4ec45371543bfba3678ebb82caf6d>:0

In the Discord I’ve been told that I cannot pass complex objects, string, int float etc. only.
So I tried to pass the Handle, and obtain it at the Handler once again.

Player player = Players[handle];

Which causes:

Error invoking callback for event playerConnectSuccessful: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.

Ah yes, that sounds right.

In my experience, even though the .Handle on a Player returns a string, and Players will accept a string as an index, it’s actually “better” to use an int (I guess since an int can be used as a proper index?), so Player player = Players[int.parse(handle)] is what you want. Only on the server is handle a string not an int, no idea why lol.

Anyway, do you actually check the Player is not null before trying to access it, something like this?

Player player = Players[handle];

if (!(player is null))
{
    Debug.WriteLine($"Player connected, and their name is {player.Name}!");
}
else
{
    Debug.WriteLine($"A player connected, but their handle ({handle}) couldn't be found. Did they disconnect?");
}

Not to say you’re not already doing this, but the server is very delicate; unlike the client where a script can crash and it’s not a huge deal, the client will continue to run, on the server certain errors will completely crash the server, such as some null ref errors, calling functions on entities that don’t exist, etc. So it’s good habit to do checks like these.

1 Like