DeveloperBreeze

Unity Programming Tutorials, Guides & Best Practices

Explore 1+ expertly crafted unity 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

     using UnityEngine;
     using Unity.Netcode;

     public class PlayerController : NetworkBehaviour
     {
         public float moveSpeed = 5f;
         public float rotateSpeed = 200f;

         void Update()
         {
             if (!IsOwner) return; // Only allow control by the local player

             float move = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
             float rotate = Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime;

             transform.Translate(0, 0, move);
             transform.Rotate(0, rotate, 0);
         }
     }

This script allows the player to move forward and backward using the Vertical axis and rotate using the Horizontal axis. The IsOwner check ensures that only the player who owns the object can control it.