Throwing an Error when trying to use multiplayer peer

Godot Version

Godot 4.2.2 - stable

Question

Iam getting this error:
Invalid set index “multiplayer_peer” (on base: ‘null instance’) with value of type ‘ENetMultiplayerPeer’.

So i made the following code, and it works great when i try it in the editor, but when i try hosting and joining from 2 different device it send this error. I noticed it only send the error when there is already a client or host created from either device, so basically i can create the host, but can’t connect to it from the other device as it throw that error. Thanks for your help.

Here is the code:

var multiplayer_peer = ENetMultiplayerPeer.new()
const PORT = 1234


func _ready():
    multiplayer.allow_object_decoding = true


func create_server():
    multiplayer_peer.create_server(PORT)
    multiplayer.multiplayer_peer = multiplayer_peer   <-- Error Here
    
    multiplayer.peer_connected.connect(_on_peer_connected)
    multiplayer.peer_disconnected.connect(_on_peer_disconnected)


func join_server():
    multiplayer_peer.create_client(get_ip(), PORT)
    multiplayer.multiplayer_peer = multiplayer_peer   <-- Error Here

you should always catch the error of the create_client/host method:

var error = multiplayer.create_...(client/host)
if error:
    print(error)

This should help understand the problem

There is not any error on the multiplayer.create(client/host) functions, its on this line that the error occurs:
multiplayer.multiplayer_peer = multiplayer_peer

Please read more carefully what i said.

Well you should still do it, since your code doesnt show anything wrong. Also try changing the port and see if that fixes it.
EDIT:
Your multiplayerAPI doesnt seem to exist. Do you do anything else with the multiplayer property anywhere?
Also this script has to extend atleast Node

2 Likes

I did it as you said, there was still no error appearing regarding to it.

However, by checking why my multiplayerAPI did’t existed, i found the issue:
I was instantiating the class in another script, but the class need to be inside the scene tree to access the MultiplayerAPI, so i only had to add this node as a child to the node i was instantiating it in.

Thanks for your help !

2 Likes