There are two realms in networking on S&box. The client, and the server:
Client: Each person playing in your game.
Server: The process that is responsible for orchestrating your game with all of the clients in it.
By default, both sides will know nothing about each other. But networking allows either side to communicate and keep each other in sync. While the same code will be run on both the client and server. No variables and state information you make are shared between them. Due to this, all variables you create whether they are created the exact same way or not will become out of sync when something is done on only one realm. This is where networking comes in. This allows you to share information between both the client and the server.
Upon a client joining you will find the above in your console. Notice how they are not the same.
ClientJoined method is only called on the server. Because of this, only the server adds one to the
NumClients field. Since this integer is not networked the clients will never get an up-to-date
With a small edit to the code like so:
Now when a client joins you will find the above in your console.
Three things were changed:
partialkeyword was added to the class. The S&box code generator will attach more code to the class in a separate file to support networking types and so
partialis required for the code to compile.
- The field was turned into a property. This is because S&box networking cannot work with fields. It requires a property. (What's the difference?)
Netattribute was applied to the
NumClientsproperty. This is to mark the property for networking.
- Not all classes are capable of networking. Only
BaseNetworkableclasses, and anything derived from those are networking capable.
- Not all types can be networked, see this list for available types.
- Properties marked with the
Netattribute cannot be edited by the client. It will not produce an error, just nothing will happen. If you have code that requires updating on the client side then you need prediction.
You can add the
Change attribute to your networked property and it will call On[Property]Changed on your class on the client side.
You can read the dedicated page for network callbacks here