Cannot Recreate an EnetMultiplayerPeer

Godot Version

4.3

Question

Hello,
I am trying to have a menu where a player could decide to host or join.
Quitting back to the menu and connecting back gets me this error :

  <C++ Error>    Parameter "host" is null.
  <C++ Source>   modules/enet/enet_connection.cpp:318 @ _create()
...

I wrote this small node for testing and getting the same error:

using Godot;

public partial class Test : Node
{
    public override void _Ready()
    {
        base._Ready();
        Host();
        Quit();
        Host();
    }

    public void Host()
    {
        Multiplayer.MultiplayerPeer = null;
        var _peer = new ENetMultiplayerPeer();
        var error = _peer.CreateServer(1234);
        if (error != Error.Ok)
        {
            return;
        }
        GD.Print("OK");
        Multiplayer.MultiplayerPeer = _peer;
    }

    public void Quit()
    {
        Multiplayer.MultiplayerPeer = null;
    }
}

I tried with calling Close on the MultiplayerPeer without success

On which line did the error occur ?

The error happens on calling Host a second time while trying to call

        var error = _peer.CreateServer(1234);

I tried the gdscript version and it works, so it looks like a C# only error.

extends Node

func _ready():
	host()
	quit()
	host()

func host():
	var peer = ENetMultiplayerPeer.new()
	var error = peer.create_server(1234)
	if error:
		print(error)
	multiplayer.multiplayer_peer = peer

func quit():
	multiplayer.multiplayer_peer = null

I figured it out, you need to manually dispose of the object. It also errors if you fiddle with the host, like if you set up compression so you might need to dispose of both :

        var peer = (ENetMultiplayerPeer)Multiplayer.MultiplayerPeer;
        peer.Host?.Dispose();
        Multiplayer.MultiplayerPeer.Dispose();
        Multiplayer.MultiplayerPeer = null;
1 Like