I am making 2D Top-down shooter in network. I spawn a gun on Players hand position. My problem is, when Client spawn his gun, it has some kind of delay. When client is moving, the gun is not following him well, just appearing by him within 1/4 Sec. It just "jumps" to player. The problem is only on the client-side, the host is fine.
Gun is in spawnable components, it has Network Identity and authority, its also has Network Transform. Player has same components.
Here is my Code:
public class Player : NetworkBehaviour
{
[SerializeField] float speed = 10f;
[HideInInspector] public GameObject playerGun;
public GameObject gunPrefab;
void Update()
{
Movement();
if (Input.GetKeyDown(KeyCode.I))
{
CmdGetGun();
}
}
private void Movement()
{
Vector3 position = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * Time.deltaTime * speed;
transform.position += position;
MouseMovement();
}
private void MouseMovement()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
mousePosition.Normalize();
float rotation_z = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
}
[Command]
public void CmdGetGun()
{
Debug.Log("SPAWNING A GUN");
GameObject playerGun = (GameObject)Instantiate(gunPrefab, GetComponentInChildren<HandHolder>().transform.position, GetComponentInChildren<HandHolder>().transform.rotation, GetComponentInChildren<HandHolder>().transform);
NetworkServer.Spawn(playerGun);
RpcSetGunOnClients(playerGun);
}
[ClientRpc]
private void RpcSetGunOnClients(GameObject playerGun)
{
this.playerGun = playerGun;
}
Here are Player and Gun components :
Im trying to find the solution for days.
I tried even without using NetworkTransform on a gun, but then i had a problem with new players joining server. They couldnt see updated position of already spawned guns.
I hope somebody can help me.