In this lesson, you will learn how to encapsulate game-specific rules directly within networked objects by extending the NetworkBehaviour class.
Moving Beyond Simple Data Syncing
While NetworkObject allows Unity to identify and track an entity across the network, NetworkBehaviour is the class that gives that entity "intelligence." By inheriting from NetworkBehaviour instead of the standard MonoBehaviour, your script gains access to the networking lifecycle, allowing your logic to react precisely to changes in server authority or client connection states.
Responding to Network Events
The core power of NetworkBehaviour lies in its ability to execute code only when specific networking conditions are met. For example, you shouldn't allow a client to calculate player damage locally, as that invites cheating. Instead, you use lifecycle callbacks like OnNetworkSpawn to initialize your logic only once the object is fully synced on the network.
Consider this implementation for a networked interaction object:
using Unity.Netcode;
using UnityEngine;
public class NetworkedDoor : NetworkBehaviour
{
public override void OnNetworkSpawn()
{
// Only run initialization logic once the object is live on the network
if (IsServer)
{
Debug.Log("Door initialized on the authoritative server.");
}
}
[ServerRpc(RequireOwnership = false)]
public void RequestToggleDoorServerRpc()
{
// Logic inside here only executes on the server
ToggleDoorState();
}
}
Why Logic Placement Matters
By placing your game rules inside a NetworkBehaviour, you centralize the control flow. The IsServer and IsClient flags allow you to write branching logic that keeps your game simulation stable. When you use these behaviours, you ensure that the logic governing an object is tightly coupled with its network state, preventing scenarios where a client tries to process an event that hasn't officially "spawned" or been authorized by the server yet. This pattern creates a robust foundation for building complex, multiplayer-aware gameplay systems that respect the authority of the server.
Key Takeaway: Extending NetworkBehaviour allows you to inject custom, authority-aware game logic directly into the networking lifecycle, ensuring your game rules execute consistently across all connected clients.