Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Good Networking Practices!

Discussion in 'Multiplayer' started by seon, Jan 3, 2008.

  1. seon

    seon

    Joined:
    Jan 10, 2007
    Posts:
    1,441
    I would like to start a thread that discusses all good working practices that involve networking. Ask questions here or post good ideas and solutions.

    I am going to start by asking a question about closing/finishing a network game... what is the correct way to exit a network game cleanly?

    The obvious thing is:-

    Network.Disconnect();

    But what other cleanup should we do?
     
  2. jashan

    jashan

    Joined:
    Mar 9, 2007
    Posts:
    3,304
    I have a game where you have "game sessions" which take place in one level, and it's obviously a good idea to make sure that any buffered RPCs are being cleaned up before and/or after any particular session. I do that on "game over", which in fact just means "game session over", and when loading the level (which is starting the session).

    Also, I need to keep track on the server of the logged in NetworkPlayers and do some cleanup when "everyone's gone" (just like after a good party ;-) ). I do this by simply keeping a List<NetworkPlayer> networkPlayers where I add and remove the players when they're being added or removed.

    That then looks something like (C#):

    Code (csharp):
    1.  
    2. void OnPlayerConnected(NetworkPlayer player) {
    3.     networkPlayers.Add(player);
    4.     log.InfoFormat("Player connected {0}:{1}, currently {2} players online",
    5.         player.ipAddress, player.port, networkPlayers.Count);
    6. }
    7.  
    8. void OnPlayerDisconnected(NetworkPlayer player) {
    9.     networkPlayers.Remove(player);
    10.     log.InfoFormat("Player connected {0}:{1}, currently {2} players online",
    11.         player.ipAddress, player.port, networkPlayers.Count);
    12.     if (GameData.Instance.IsStandaloneServer  networkPlayers.Count == 0) {
    13.         log.InfoFormat("No more players, cleaning up...");
    14.         GameData.Instance.Teams.Clear();
    15.     }
    16.     Network.RemoveRPCs(player);
    17.     Network.DestroyPlayerObjects(player);
    18. }
    19.  
    What you can also see in this code-snippet is that I have a singleton GameData which knows whether or not this is a "Standalone server". But that, I can use different code paths where needed. I have a checkbox "IsStandaloneServer" in a game object component in my startup scene (probably would be best to have that in a "NetworkingStuff" game object, that handles all these things and is always available and accessible from everywhere via a "Unity-conform" singleton).

    Jashan