DeveloperBreeze

C Sharp Programming Tutorials, Guides & Best Practices

Explore 1+ expertly crafted c sharp tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Developing a Real-Time Multiplayer Game with Unity and C#

Tutorial August 14, 2024
csharp

     public class PlayerController : NetworkBehaviour
     {
         public GameObject bulletPrefab;
         public Transform bulletSpawn;

         void Update()
         {
             if (!IsOwner) return;

             // Movement code...

             if (Input.GetButtonDown("Fire1"))
             {
                 ShootServerRpc();
             }
         }

         [ServerRpc]
         void ShootServerRpc()
         {
             GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
             bullet.GetComponent<NetworkObject>().Spawn();
         }
     }

In this example, when the player presses the fire button, a ServerRpc is called to spawn a bullet on the server, which is then synchronized with all clients.