Page 1 of 1

[Godot 4.1.1] How to setup client and server in the same game instance?

Posted: Sun Jul 23, 2023 1:08 am
by agrimminck
Hello there!

I'm trying to get a game instance that can run a server AND a client at the same time, which, as the docs say, should be able to be done with the functions SceneTree.set_multiplayer() and SceneTree.get_multiplayer()
https://docs.godotengine.org/en/stable/ ... erapi.html
https://docs.godotengine.org/en/stable/ ... etree.html


Quote from the MultiplayAPI docs on Godot's page:
It is possible to override the MultiplayerAPI instance used by specific tree branches by calling the SceneTree.set_multiplayer method, effectively allowing to run both client and server in the same scene.


Right now I only have this code to try to recreate the behaviour. You have to run 2 debug instances to make it work

Code: Select all

extends Node2D

func _ready():
  var peer := ENetMultiplayerPeer.new()
  if peer.create_server(3000) == ERR_CANT_CREATE:
    peer.create_client("localhost", 3000)
    multiplayer.multiplayer_peer = peer
#    get_tree().set_multiplayer(multiplayer, "/root/helloworld")
  else:
    multiplayer.multiplayer_peer = peer
#    get_tree().set_multiplayer(multiplayer, "/root/helloworld")
    

@rpc("any_peer") func hello_world():
  print("hello_world")

func _physics_process(delta):
  if Input.is_action_just_pressed("ui_accept"):
    hello_world.rpc_id(1)

But if you uncomment the commented lines, it does not work. It gives out this error
Image


Here you have the link to download the minimal project
https://www.mediafire.com/file/zuubl16u ... t.rar/file


Do anyone know how to properly execute these functions to achieve what I asked?


Thank you very much!

Re: [Godot 4.1.1] How to setup client and server in the same game instance?

Posted: Sun Jul 23, 2023 9:01 pm
by grey
you can do it but you can't have both in the same subpath ( https://docs.godotengine.org/en/stable/ ... ultiplayer )

this is how i do my server in 4.1

Code: Select all

var server := ENetMultiplayerPeer.new()
var multiplayer_api: MultiplayerAPI
multiplayer_api = MultiplayerAPI.create_default_interface()
server.create_server(port, max_peers)
get_tree().set_multiplayer(multiplayer_api, self.get_path())
multiplayer_api.multiplayer_peer = server