Pulsar is a modern team based space combat game. There will be 4 different game types but Domination is what makes Pulsar really special. In Domination the objective is to destroy all the competing team’s base and take control of the system. However, it’s not just about combat; we’ve added a touch of strategy through the use of team resources. Teams will need to reach a science level of 10 before they’ll acquire the right weapons necessary to take out an enemy base. To reach each science level teams will need to acquire resources. The more resources, the faster your team can level up. Use your resources wisely because too few spent on upgrades can leave you vulnerable to attack, but spend too much on upgrades and your leveling will take too long. Die too much and lose valuable resources to respawn. With each new science level also comes new upgrades, so don’t waste time, help with mining to speed things along. Fierce dogfights will ensue while teams race to reign victorious.

Report article RSS Feed Unity3D Networking eBook by 3DMUVE

I’ve been working with Unity3D for a little while now and I’ve found it to be one of the easiest commercial engines I’ve worked with, while still offering considerable power and flexibility. I further found the Networking to be very easy and straight forward, but I have been doing networking for many years so it was easy for me to pickup. I'm always having people ask me about networking, and I thought Unity3D is a great platform for people to start, so I’ve develop an eBook to help you.

Posted by 3dmuve on Feb 7th, 2013
Basic Server Side Coding.

A Step by Step Guide to Networking with Unity3D



By: Laurence Grant, 3DMUVE Indie Games

This eBook covers all aspects of networking for the client and the server, using the very easy networking API's from Unity.  It's intended for beginner to intermediate.  This eBook builds the simplest application from the start, so you aren't consumed by an existing (and very complex) application from the start. You can get your arms around the concepts and quickly be on your way to developing your own multi-player networked games.

With your support I hope to develop an advanced eBook at some point in the future.

The full eBook is available for download from my blog here. or can be downloaded from the Unity3D app store.

Here's what others have had to say:

Great tutorial

All networking principles are explained in detail,
with great examples. A must-read

I just pretty much finished my network coding for
my game with just this tut

Thanks for the great tutorial! I now have much
better understanding of how networking works

Just what is needed

Good examples with code ready to
be used in your own project!


To download the entire eBook please visit my blog here.

To see details of what’s covered I’ve included the Table of Contents and the first 6 pages of the Introduction  below for your review.

Thanks again to all that have supported the eBook and made it one of the most popular references for Unity3D Networking!


Table of Contents

Introduction .............................................................. ......................... 6
Game Networking Engine Designs .................................. ......................... 8
     Master Game Server (MGS) ..................................... .......................... 8
     Peer-to-Peer (P2P) ................................................ .......................... 8
     Game Server (GS) .................................................. .......................... 9
     Game Networking Engine Styles .............................. .......................... 9
          Dedicated / NON Client .................................... .......................... 9
          Non Dedicated / With Client ............................. ......................... 10
          Relay ............................................................. ......................... 10
          Authoritative ................................................... ........................ 10
          Hybrid ............................................................ ........................ 11
     LAG ..................................................................... ...................... 13
Network Connectivity and Firewalls .............................. ....................... 14
     IP Addresses and Ports .......................................... ........................ 14
          Network IP Address .......................................... ........................ 14
          IPv4 addresses ................................................. ........................ 14
          Network Port .................................................. ........................ 15
     Network Address Translation or NAT ....................... ......................... 15
     NAT Punch Through / NPT ..................................... ........................ 17
General Coding Overview ............................................ ......................... 19
     Converting between C# and JavaScript .................... ......................... 19
     Tags ................................................................... ......................... 20
     Layers ................................................................. ........................ 20
Overview of our Networking Tutorial: ........................... ......................... 21
     Demo Overview ..................................................... ........................ 21
     Basic Networking API’s ........................................... ........................ 22
           TCP vs UDP: .................................................... ........................ 22
     Unity3D Networking API’s ....................................... ........................ 22
          NetworkView ................................................... ........................ 22
     Instantiating a Networked Object ............................ ....................... 24
Building our Game: ..................................................... ........................ 24
      Building the Game Level: ....................................... ........................ 24
          Creating the Floor ............................................ ........................ 25
          Creating the Scenery: ....................................... ........................ 25
     Creating the Player Character ................................. ........................ 25
          Player Controller: ............................................. ........................ 26
     Player Spawn Area: ................................................ ........................ 29
     Pickup Spawn Area: ............................................... ........................ 29
     Overview of Networking Classes we’ll create for our Demo .................. 31
Analysis and Code of each Network Class ....................... ........................ 34
     NetworkMasterServer: ........................................... ........................ 34
     NetworkLoadLevel: ................................................ ........................ 42
          LoadLevel ........................................................ ........................ 43
          OnPlayerDisconnected ...................................... ........................ 48
          PlayerSpawn Public Variables Setup .................... ........................ 50
          Renaming Remote Objects: ................................ ....................... 54
          PlayerSpawn code: ........................................... ........................ 54
     NetworkRigidbody: ................................................ ........................ 57
          NetworkRigidbody OnSerializeNetworkView .......... ........................ 58
     Working with Pickups: ............................................ ........................ 62
          InstantiatePlayer: ............................................. ........................ 62
          BallSpawnManager: ........................................... ........................ 62
          BallController: .................................................. ....................... 62
          BallManager: .................................................... ....................... 62
     InstantiatePlayer – Updated for Networking: .............. ....................... 64
           InstantiatePlayer Code ..................................... ........................ 65
     BallSpawnManager: ................................................ ........................ 68
          BallSpawnManager Update ................................. ........................ 68
          BallSpawnManager OnSpawnBall ......................... ........................ 69
          BallSpawnManager OnInitBall .............................. ....................... 69
          BallSpawnManager Code: ................................... ....................... 69
     Ball Controller: ..................................................... ........................ 74
          BallController Update ........................................ ....................... 74
          BallController OnCollisionEnter ........................... ....................... 74
          BallController OnPickupBall ................................ ....................... 74
          BallController OnThrowBall ................................ ........................ 75
          BallController UpdatePlayerState ........................ ........................ 75
          BallController OnUpdatePlayerState .................... ........................ 75
          BallController Code: .......................................... ....................... 75
      Ball Manager: ....................................................... ........................ 80
          BallManager Update .......................................... ........................ 80
          BallManager OnCollisionEnter ............................. ........................ 80
          BallManager ReSetBallBackToSpawnArea .............. ........................ 80
          Ball Manager Code: ........................................... ........................ 80
     Updating Prefabs: .................................................. ........................ 83
          Updating the Player Prefab ................................ ........................ 83
          Updating the BallPickup Prefab .......................... ........................ 84
     Initializing Public Variables: ..................................... ........................ 85
          BallSpawnManager Public Variables: .................... ........................ 85
          BallController Public Variables: ........................... ........................ 86
          BallManager Public Variables: ............................. ........................ 87
CONGRATULATIONS, we’re done .................................. ........................ 88
Appendix A - Managing dynamic Objects ........................ ........................ 89
      Creating a Throwing Spear ..................................... ........................ 89
      Spear Code: ......................................................... ....................... 90
          SpearController Code: ....................................... ....................... 90
          SpearManager Code: ......................................... ....................... 94
          Spear Controller Variables: ................................ ........................ 95
          Spear Manager Variables: ................................... ........................ 97
     Buffered RPC commands ......................................... ........................ 98
     Networking Groups ................................................ ........................ 99
     SetLevelPrefix ....................................................... ....................... 100
Appendix C – Try This .................................................. ....................... 101
Appendix D – Object to Script Associations .................... ....................... 102
     MasterGameServerLobby Level ................................ ....................... 102
     TestGameLevel Level .............................................. ...................... 102
Conclusion ................................................................ ....................... 103

To download the entire eBook please visit my blog here.


I've included a section here from the Introduction:

Introduction

Hi everyone. Thanks for reading my eBook. There are several networking tutorials I’ve found on Unity3D Networking, but they were inadequate to me. They mostly said things like:

     • copy this
     • paste this
     • do that
     • delete this
     • etc…

Although it was ok for me as I’ve had networking experience in the past I thought goodness, anyone who hasn’t had experience with networking in the past might really struggle with these tutorials as they don’t explain what they are having you do or why. Therefore, I’ve decided to write my own tutorial here to help anyone who wants to add networking to their Unity 3D game. I’m sure for some game networking experts, they might have different opinions on a lot of what I introduce here, and I don’t claim to be an expert by any stretch. I design very practically and implement a good-enough approach as we are making games after all . My intent with this tutorial is to serve as an introduction to game networking and to provide the skills and knowledge required to get you started developing multi-player games in Unity3D. Where you take it from there is up to you. I will have a few areas of “do this”, “paste that”, but they will almost always be lead with an explanation of what you’re doing and why.

Special Thanks
Much of the original networking code I’m using was taken from the Star Trooper Multi-Player Tutorial by Andrius Kuznecovas. Without his sample I would have had a much harder time getting up to speed on Unity3D networking. I’ve taken his concepts and tried to provide a lot more detail on what I’m doing and why I’m doing it. I’ve also replaced the use of Star Trooper with a very simple demo that we will build inline ourselves in this tutorial. I hate tutorials that use existing code that does a whole lot more than what we’re trying to teach. I like to dumb it down to the basics and show what’s needed without a lot of extra complexity. I hope you find this tutorial beneficial.

To accompany this eBook I’ve included two additional files:

3DMUVE Networking Tutorial for Unity3D - Code Only Package.unitypackage
This is a Unity3D Package File containing all the source code discussed in this eBook. Instead of retyping the code, or trying to cut/paste, it’s best to use this package. Leverage the eBook to understand what’s being done and following the steps on how to create the ingame objects and assemble everything. If you run into difficulty the next file includes the completed project in its entirety.

3DMUVE NetworkingTutorial for Unity3D full Unity3D Project.zip
This is a copy of the full Unity3D project that I developed for this eBook. I would recommend only using it if you get stuck and need to look at a completed project to try and figure out where things differ. If you find any mistakes between what’s documented in the eBook and this project please let me know.

First, let’s start with understanding some gaming concepts. I’m going to focus on just one, the “Hybrid Engine”, which in my opinion is the most functional style of networking for most multi-player games, especially real-time games. It’s important to understand there are many ways to implement a networked game, and even though we might use the same underlying low level calls, one design isn’t necessarily better than another. Each game has different needs and as a lead designer and developer we need to work together to decide which is best for our games. I lean towards what I’ve coined as the “Hybrid” style networking engine, but this isn’t an industry term, and I’m sure a lot of other gaming implementations do something similar. We will cover “Authoritative”, “Relay” and “Hybrid” and even develop a little of each since “Hybrid” is basically a combination of the other two.

To start with we’ll discuss:

     1. What a Master Game Server is
     2. What a Game Server is
     3. LAG, Prediction and Smoothing
     4. Connectivity and challenges with firewalls,
     5. Coding Sample
          a. Building a sample application to test our code
          b. Finally we’ll discuss the Unity 3D API’s used to implement the code.
               i. NetworkView
                    1. State Synchronization
                    2. RPC calls
              ii. Instantiating of networked objects
              iii. Managing networked objects

This tutorial develops a Windows based game, but from a networking perspective I believe everything covered will apply to all the Unity3D supported platforms. The only real thing that makes this Windows specific is the Input checks of the keyboard and mouse. If you wanted to port this tutorial to run on an iPad for example it should work just fine but the Input would have to be updated to use a less brute force approach to checking Input. I haven’t tried this yet but unless the Unity3D networking API’s are doing something under the covers, I believe you should be able to play cross-platform too, which means a user on an iPad should be able to interact with a user on a PC for example. I haven’t read anywhere that this is blocked.

Game Networking Engine Designs
There are many ways you can design a networked game. Some games run a single game server on a publicly accessible computer somewhere and gamers can connect to it remotely without entering anything special because the client is already configured “at the factory” if you will to connect to the one hosted game server. In other cases the user might be required to enter the credentials of the game server to control what game they connect to and in another design there might be a menu displayed which allows the game client to choose what they want. We’ll examine these in a little more detail, and then we’ll develop a sample that uses a dynamically generated selection menu.

Master Game Server (MGS)
A Master Game Server (MGS) can be thought of as a lobby server. It’s where your game client first connects to see what games are already available. You can choose to join an existing game or start a new game. Unity provides a MGS for testing as well as the source code for you to run your own MGS customized for just your game, available here (http://www.unity3d.com/master-server/index.html). In its simplest form an MGS provides a list of existing games. It might show the game name, a description, number of connected players, information about location or network lag, or other details to help you decide what game to join. You might create/join a private game for just your friends to play. You can extend the MGS to support buddy lists, friend chat, and other features to help the gamers with game matching or the social aspects of cooperative play. The MGS does NOT perform any game related tasks, except with initial connectivity needs. It’s strictly the central hub for match making and coordination of players joining games. Once a game is underway it’s handled by the Game Server (GS) and has no further coordination with the MGS.

Peer-to-Peer (P2P)
A P2P game networking design is when each game client has a network connection to every other game client and they’re able to send commands to one another to provide appropriate updates. Consider a two player game such as chess, each player client would tell the other player client of its move, and they would continue to exchange updates throughout the game. In the P2P design each client is equal in power and makes decisions for the game. Its common in a turn based game where the gamer takes a turn and the local game client performs 100% processing of that turn then tells the other gaming clients what it did. As each gamer takes their turn, 100% of the processing is performed by the local game client and the results are passed on. It’s less common to see this style implementation used in a fast paced game such as a FPS.

Another challenge with P2P is an increased risk of cheating. If there are no controls in place across all game clients to ensure each move being performed is valid, then a compromised game client could conceivably cheat with no restrictions.

We also don’t see P2P used often with games requiring large numbers of users due to the complexity of ensuring all clients can connect directly to all other clients. When we get into coding we’ll show how to setup NAT Punch Through (we’ll discuss in more detail later), a technique used to bypass firewalls which would otherwise prevent gamers from connecting to a non-publicly hosted game server. This process is rather tricky for game clients connecting to a single game server. If all clients had to connect to all other clients we’d have to perform this step again and again which can be very complicated, prone to failure, and not necessarily needed.

Game Server (GS)
The Game Server (GS) is the main coordinator for a new game. The main purpose of the GS is to coordinate connectivity of all the clients. Most games don’t have every client connect directly to every other client, unless it’s only a two player game (or very few players.) We usually design a GS as the central hub for all clients to connect. A client talks to other clients by sending commands to the GS and the GS relays those commands to all the other clients.

Game Networking Engine Styles
There are several common types of Game Servers people implement:

Dedicated / NON Client
    • The Dedicated Game Server doesn’t also run a client. It’s often used for MMOPG’s where the
       players themselves don’t have the option to host their own game, but can only join an existing
       game. Another use case is to let the player host their own game on a dedicated computer.
       Because there is no client also running performance is improved which can help support more
       clients, or possibly reduce lag due to the server running slow and contending for resources
       with the client. We don’t see this use case often as it requires a second dedicated server
       which isn’t usually available. Some games focused at a small population of hard core games, such
       as Half Life’s Counter Strike, will sometimes provide the option for a player hosted dedicated
       Game Server.

Non Dedicated / With Client
    • Most games that allow the player to host their own game allow the player to also run as a player
      (client) on that game at the same time, from the same computer. The benefit is that it makes it
      easy for a player to host their own game without needing a second computer or complex
      networking setup. The disadvantage is that the GS is also coordinating all networking to all clients
      and can affect the game play for everyone if the local client is slowing things down. It can also
      affect the local client because the server is contending for resources.

    • We’ll be developing a non-dedicates game server for our game, but we’ll be offloading some of
      the traditional Game Server processing to other clients using my Hybrid approach.

Regardless of Dedicated or Non-Dedicated, the following GS types can exist with either of the above mentioned types:

Relay
    • A Relay GS acts more like a peer-to-peer implementation where all the work is being performed
      on the clients, and the GS is just used to send packets between a client and all other clients.
      This provides the best performance as actions can occur locally as soon as the player does
      something, and gets updated to other clients asynchronously. However, because of this it lends
      to hacking/cheating and can also provide unexplained results due to lag and other issues. (Ie: a
      player explodes but on the remote client nothing caused the explosion due to lag or packet
      drop, at the same time on a different client a bomb went off killing the player, and on a third
      client the player was away from the bomb but dies a short time later for no apparent reason,
      when the session state gets replicated)

    • These days with controlled client devices such as smart phones, ipads or consoles, we don’t
      need to be as concerned with hacking the way we are on PC/MAC titles.

Authoritative
    • Authoritative GS is just the opposite of the relay server. In this model the client sends all
      commands to the GS and the GS decides if the command is acceptable and performs the
      appropriate action, such as walk forward, then updates all the clients with the new position and
      orientation of all objects. This is common in an MMORPG where the action is more turn based,
      but less than ideal for a real-time FPS which has fast paced action and expects near real-time
      response. All clients are in lock-step with each other, but due to lag of the GS, can feel slow and
      unnatural to the player. Some games use an Authoritative approach but add a local prediction so
      it feels more accurate. In this case a player requests to move. It sends the request to the server
      but at the same time assumes the server will approve it so the local move is started. This way it
      feels responsive to the player but the GS still has the final say and will put the player back where
      he was if it doesn’t approve the request.

Hybrid
    • What I recommend for most multi-player games is what I’ve coined as the Hybrid style. This
      incorporates the best of the relay and authoritative servers in a well balanced way providing the
      most flexible gaming experience. In Hybrid the player performs an action which occurs
      immediately then tells the other clients through the GS so they can refresh what the other
      players are doing appropriately. This is similar to the peer-to-peer. However, when it comes to
      things that affect other players, then each player is responsible for the decision of things it
      controls, which is similar to the Authoritative approach but instead of the GS being the
      authoritor, each client is the authoritor for the objects they control/manage. Some objects in
      the scene/level aren’t tied to a player such as the trees, or power-up items. In this case the GS
      would be the authoritor for those items. Let’s go through an example:

        i. Let’s say we shoot a missile projectile. We start the animation immediately on our client so we
            experience no lag.
        ii. We tell the GS what we did and it tells the other clients so they too can instantiate the    
            projectile. We’ll refer to this remote copy of the missile as the missile’s AVATAR.
        iii. As the missile travels on the originating client, the client is sending updates through the GS
            so each remote client knows the current position and orientation
        iv. On the remote clients we use something called prediction and smoothing (covered later) to
            update the missiles avatar on the remote clients
        v. Now back on the original client the projectile hits another player. The appropriate response
            is to show the collision which we do “LOCALLY”. Next we’d want to apply damage to the
            other player, but we DON’T do that. Since we don’t control the other player that was hit we
            aren’t responsible for applying damage, we’re NOT authoritative for the hit player.
        vi. We could choose to either send a message (through the GS) to the player we hit and ask it
            to apply the damage, but I don’t particularly like this approach. Instead what I let happen is
            once the projectile on the remote players computer hits the player then that remote player
            will process its own damage updates.

                    1. If you’re paying attention and getting it so far you might realize the missile was just
                       destroyed on the original client, so I’m no longer sending/receiving updates.
                       Therefore doesn’t the missile avatar just stop?
                    2. Well it would except we’re still using prediction which will keep the avatar moving
                        along its previous trajectory. The only extra thing we do on the avatar is manage a
                        timer to self destruct the avatar after a certain period of time since we’re no longer
                        receiving updates from the original client.

                                 a. A few other approaches we can implement include:
                                           i. When the originating missile is destroyed we send a packet to all the
                                              remote missile avatars to take over their own navigation until they
                                              either hit something or their timer expires.
                                           ii. From the time we originally instantiate the missile on the remote
                                               clients we can let each remote client handle its own local
                                               movement, never needing to send network updates as the missile
                                               travels. This is also a perfectly acceptable technique since a 
                                               missile’s trajectory is mathematical and very consistent. However,
                                               when it hits something on a client that controls what was hit and
                                               therefore applies damage to what was hit, we should send a
                                               command to all other clients instructing them to terminate the
                                               missile so we don’t perform additional damage on a secondary client
                                               because we hit something there too, at a later point in time.
                    3. There are many ways to consider implementing this and I’m just suggesting one way
                       to do it.
        vii. If the missile avatar hits the remote player on the client controlling the remote player, then
             that remote player applies damage to itself and decides if it was destroyed. If it was
             destroyed the remote client will send a destroyed message to the GS telling all the other
             clients it was destroyed.
        viii. If the projectile never hits the remote player, because the remote player was in a different
             place due to lag. Then no damage is done. This will feel the most natural to all players as the
             original player will see a shot hit, but no death, and the remote player continues on without
             incident.
        ix. Someone has to be in charge of the decision making and I prefer each player to be in charge
            of his own character along with any other objects that character owns/controls. This is the
            crux of the Hybrid model.
        x. In the case of an object that’s neutral, such as a tree that can take damage, then the GS is
            the owner of all neutral objects and will be responsible for performing any damage incurred.
            This is a good reason to have a dedicated GS, so the extra processing for scene objects
            wouldn’t affect a player client running on the same computer.

To download the entire eBook please visit my blog here.

Post comment Comments
figalot
figalot Feb 10 2013, 11:11pm says:

Im interested I am just wondering what the demo scene is? What does it show?

+1 vote     reply to comment
3dmuve
3dmuve Feb 11 2013, 1:22am says:

Thanks for your interest in my Unity3D Networking eBook.

The demo that I have you build through the eBook is an extremely simple single level. There is a ground to walk on, a large square in the center of the screen, and we create two player spawn points then two weapons spawn points. As players join they are randomly spawned at one of the two spots. Each player is carrying a spear and can throw it, or they can walk to one of the two weapon spawn points and pickup another weapon (an orb). I show and discuss several methods for instantiating, maintaining object sync between players, handling updates when a player walks or a weapon is thrown, cleaning up on collision, death, respawn, etc...

The demo we build isn't intended to be really usable as a game. It is intended to provide a solid foundation for networked concepts, and how to build your own networked game. I didn't want to over complicate the tutorial with a lot of non networking stuff, so I kept that part extremely basic so the reader can focus and grasp the networking concepts.

As listed, I've gotten terrific feedback from those who have purchased the eBook. I hope you learn a lot, I think you will.

Good luck.

+1 vote     reply to comment
Post a Comment
click to sign in

You are not logged in, your comment will be anonymous unless you join the community today (totally free - or sign in with your social account on the right) which we encourage all contributors to do.

2000 characters limit; HTML formatting and smileys are not supported - text only

Icon
Pulsar
Platforms
Windows, Mac, Web
Developed By
3dmuve
Engine
Unity
Contact
Send Message
Official Page
Pulsar.3dmuve.com
Release Date
TBD
Game Watch
Track this game
Tutorial
Browse
Tutorials
Report Abuse
Report article
Related Games
Pulsar
Pulsar Indie Multiplayer First Person Shooter
Related Engines
Unity
Unity Commercial Released May 30, 2005