Unet - spawning bullets, two issues

Okay, I have searched all of the internet and I can’t solve it.

I have learnt that if you spawn an object through NeworkServer (and the prefab is registered in NetworkManager) if the object gets destroyed on the server it will also be destroyed on clients. So I assumed synchronization should be spot on. It kind of works but, I get “did not find target for sync” message when I play as client. I understand that unet tries to synchronize bullet’s position, but it could be already destroyed on clients.

The other issue is that bullets when they collide with other non kinematic rigidbodies - players for example - they just like skip some physics and push other players with so much force. When played on client and shooting host player, then host player just flies off. On the other hand when host shoots a bullet and it collides with client’s player, physics seem to be ok. Bullet has NetworkTransform and SyncMode is set to Rigidbody2D.

Shooting script (attached to the player):

	void Update()
	{
		if (isLocalPlayer)
		{
			if (Input.GetKeyDown(shoot_key))
			{
				if (playerMovement.IsFacingRight) CmdShoot(Vector2.right);
				else CmdShoot (Vector2.left);
			}
		}
	}
		
	[Command]
	public void CmdShoot(Vector2 direction)
	{
		if (!isServer) return;

		GameObject instance = Instantiate(_bullet, _hotSpot.transform.position, Quaternion.identity) as GameObject;
		Bullet bullet = instance.GetComponent<Bullet>();
		bullet.SetDirection(direction);
		Destroy(instance.gameObject, 1);
		NetworkServer.Spawn(instance.gameObject);
	}

And bullet script:

public class Bullet : NetworkBehaviour
{
	public float _startingSpeed = 200;
	private Rigidbody2D rb;
	private Vector2 direction;

	void Start()
	{
		rb = GetComponent<Rigidbody2D>();
		rb.AddForce(direction * _startingSpeed);
	}
		
	public void SetDirection(Vector2 newDirection)
	{
		direction = newDirection;
	}
}

Could you explain what am I doing wrong, please?

Don’t know why you put:

    if (!isServer) return;

on your Command, remove it. I also don’t quite get it why you have AddForce on Start and then you immediately change it with SetDirection, make your mind :slight_smile: That Destroy before Spawn looks odd but I don’t think it’s the case but still odd :slight_smile: Let me know if any of it helped. Good luck.