Godot Version
4.3
Question
`I found a reddit post talking about it (https://www.reddit.com/r/godot/comments/17k0c02/peer_2_peer_multiplayer_in_godot/), and although they got close, they never solved it. The username data is being passed from client to host. When the client joins, everything is dandy, but the host cannot see the client. I think the add_child is only running on the client’s side.
Here is my script, I have attached screenshots of the problem. Thanks`
extends Node3D
var peer = ENetMultiplayerPeer.new()
@export var player_scene: PackedScene
var peer_usernames = {} # Dictionary to map peer IDs to usernames
func _on_host_pressed():
peer.create_server(9012)
multiplayer.multiplayer_peer = peer
multiplayer.peer_connected.connect(_player_connected)
sendUsername(multiplayer.get_unique_id(), GlobalScript.username)
$CanvasLayer.hide()
func _on_join_pressed():
peer.create_client("127.0.0.1", 9012)
multiplayer.multiplayer_peer = peer
sendUsername(multiplayer.get_unique_id(), GlobalScript.username)
$CanvasLayer.hide()
func add_player(id = multiplayer.get_unique_id(), usr=""):
var player = player_scene.instantiate()
player.name = str(id)
var username_label = player.get_node("Head/username")
username_label.text = "Player " + usr # Use the passed username
print(username_label.text)
# Add the player to the scene first
call_deferred("add_child", player)
func del_player(id):
# Call the function to remove the player
rpc("_del_player", id)
@rpc("any_peer", "call_local") # Calls this on the sender as well
func _del_player(id):
peer_usernames.erase(id)
var player = get_node_or_null(str(id))
if player:
player.queue_free()
@rpc("any_peer")
func sendUsername(id, passedUsername):
# Add player on all peers
add_player(id, passedUsername)
peer_usernames[id] = passedUsername # Store username in the dictionary
func _player_connected(id):
# When a new peer connects, send the existing players' usernames
for peer_id in peer_usernames.keys():
sendUsername(peer_id, peer_usernames[peer_id])