Synchronize custom resources in multiplayer

Godot Version

4.4.stable

Question

I have a custom resource with which I handle weapons, the thing is when a player switches weapon it doesn’t synchronize with the rest of the players. And I don’t know how to do it. I tried to put an RPC in the code that handles the loading of the weapon but didn’t work. Sorry for the chaotic code but I’m in a hurry to deliver this to a jam and I don’t have time to make it pretty.

@rpc("any_peer", "call_local")
func load_weapon():
	if is_multiplayer_authority():
		if current_weapon == "primary" and primary_weapon != null:
			if $Sprite2D != null:
				$Sprite2D.texture = primary_weapon.texture
				$Sprite2D.scale.x = primary_weapon.sprite_scale
				$Sprite2D.scale.y = primary_weapon.sprite_scale
				
			damage = primary_weapon.damage
			automatic = primary_weapon.automatic
			cadence = primary_weapon.cadence
			primary_selected = true
			secondary_selected = false
			melee_selected = false
			$Marker2D.position.x = $Sprite2D.texture.get_width() / 5
		elif current_weapon == "secondary" and secondary_weapon != null:
			if $Sprite2D != null:
				$Sprite2D.texture = secondary_weapon.texture
				$Sprite2D.scale.x = secondary_weapon.sprite_scale
				$Sprite2D.scale.y = secondary_weapon.sprite_scale
				
			damage = secondary_weapon.damage
			automatic = secondary_weapon.automatic
			cadence = secondary_weapon.cadence
			
			primary_selected = false
			secondary_selected = true
			melee_selected = false
			$Marker2D.position.x = $Sprite2D.texture.get_width() / 5

			
		else:
			if $Sprite2D != null:
				$Sprite2D.texture = null
			
			primary_selected = false
			secondary_selected = false
			melee_selected = true
func change_weapon():
	if Input.is_action_just_pressed("primary_weapon") and primary_weapon != null and reloading == false:
		current_weapon = "primary"
		load_weapon.rpc()
	elif Input.is_action_just_pressed("secondary_weapon") and secondary_weapon != null and reloading == false:
		current_weapon = "secondary"
		load_weapon.rpc()
	elif Input.is_action_just_pressed("melee") and reloading == false:
		current_weapon = "melee"
		load_weapon.rpc()

Seems like the current_weapon isn’t being synced, so the next load_weapon call doesn’t know which weapon to load.

You could change load_weapon to accept a weapon parameter and set the value from there. The RPC shouldn’t accept “any_peer” if it only works on the multiplayer authority.

@rpc("call_local")
func load_weapon(new_weapon: String) -> void:
	current_weapon = new_weapon
	if new_weapon == "primary" and primary_weapon != null:


# call with arguments
load_weapon.rpc("primary")
1 Like

It works perfectly, you’re my hero. Thank you very much! :sparkling_heart: