How to refer to a CharacterBody2D that was instantiated based on peerID?


Who doesn’t love netcode? After a couple of days of banging my head against a wall, I finally have some decent multiplayer network … uh… communication happening. Unfortunately this completely broke my game. What I was doing before was basically going “If you are the server you are player1, and if you are the peer then you are player2” and had a separate player1 and player2 node already created within the scene.

Of course, now I want to make it uh, better, and only have 1 player scene that get’s instantiated and changed as needed for each player when the game starts. The game should only start when all players are ready. Because of this, I am instantiating my players in the game scene which exists separately from the menu/networking scene.

I tried assigning variables to the player objects after they are instantiated, and then using these variables to assign multiplayer_authority or change the name, but unfortunately these variables go back to null almost immediately. Of course, I could just set the CharacterBody2D names to their peerID, but then I don’t know how to refer to them later in scripts.

Here is an example of some of the code in my game script that needs to directly reference a CharacterBody2D:

if player1IsRecovering:
		$Player1.isRecovering = true
		$Player1.set_velocity(Vector2(0, 0))
		$Player1.allowInput = false
		$Player1.position = $Player1.position.lerp(p1Spawn, p1RecoveryIncrement)
		p1RecoveryIncrement += 0.0001
		if p1RecoveryIncrement > 0.05:
			p1RecoveryIncrement += 0.2
		if $Player1.position.is_equal_approx(p1Spawn) or p1RecoveryIncrement >= 1:
			player1IsRecovering = false
			$Player1.isRecovering = false
			$Player1.set_deferred("allowInput", true)
			p1RecoveryIncrement = 0.0001
		$Player1.allowInput = true

If I set the name to the players peerID, I don’t have a way to reference it in bits of logic like this. Any ideas?