How to connect and disconnect signal on Godot 4 C#?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By PowerPotato

Hi folks:

I have a code fragment where I need to connect and disconnect a signal with parameters.

After read Object — Godot Engine (latest) documentation in English I found that the preferred way to do this is using the next sintax:

player.Hit.Connect(OnPlayerHit, new Godot.Collections.Array {"sword", 100 });

My code look like this:

private void HealthCharacter(Node body)
{
    if (body is Character)
    {
        Character character = body as Character;
        character.IsInvulnerable = true;
        // if (Timer.IsConnected())
        // {
        Timer.Timeout.Connect(OnDoHealth, new Godot.Collections.Array { character });
        // }
        Timer.Start();
    }
}

But this do not compile throwing the next error:

 Health.cs(38,19): El evento 'Timer.Timeout' solo puede aparecer a la izquierda de += o -=.

This translate to:

The 'Timer.Timeout' event can only appear to the left of += or -=.

So I really don’t know how could I connect and disconnect signals with parameters on the new Godot

:bust_in_silhouette: Reply From: Zenzor

Hey PowerPotato!

The new Godot 4 C# Syntax to Connect Signals is

private void HealthCharacter(Node body)
{
    if (body is Character)
    {
        Character character = body as Character;
        character.IsInvulnerable = true;
        // if (Timer.IsConnected())
        // {
                Timer.Timeout **+=** OnDoHealth;
        // }
        Timer.Start();
    }
}

Yes but with that syntax we are no able to pass arguments. I know we can do something like this

Timer.Timeout += () => OnDoHealth(character);

But in that case I don’t, know how to disconnect, because you can not do somithing like this after that:

Timer.Timeout -= () => OnDoHealth(character);

So I think i’m missing something

PowerPotato | 2023-01-19 08:03

The code is correct, maybe a bug or you just nothing get a return from your args func… Try put a Print as log to OnDoHealth(character); and see if it return anything

Zenzor | 2023-01-21 03:54