jeudi 9 juin 2016

Unity : networking part 1

In the way, to have a dedicated server, and client able to connect to it, you can use standard script from unity. One of them, draw a little hud, where you can choose to launch standalone server, a client, or client hosting server.

Another script is more usefull and manage all events upon network : NetworkManager.

For my purpose, I create my onw c# script, inheriting of networkmanager. I wish to override several events, and function, so it is the best way to do. Its name will be ShimNetworkManager.

As in any script, you have a start and update function. In the start function, I will start a server, or start a client.

When the scene will start, this script must be runned. For this, I will add in my scene, a simple GameObject. I will name it NetworkManager.
I will add as component, my newly ShimNetworkManager script.

For now, as you will launch the game, it will execute automatically this script. But how to know if I am a server, or a client?

From my mind, it will be a server, if the game is loading directly this scene.
If the load of the scene comes from an another scene, it is a player trying to connect to a client. It is my assumption.

Pass GameObject scene to scene


I spent lot of time on this question.
When you load a scene, you destroy the old one, and all object belonging to this scene, even those you have instantiated by a script.
Finally, I discover a trick that allow to pass scene to scene some GameObject. So, to know if this is a client that is loading the scene, I test the existence of this object.

I create a second scene, named authentificationLevel. In this scene, I create a GameObject named PlayerOverScene.
I create a c# script named playerScript which will contain in further articles, the information linked to user (name, id, ....).

To allow to an object to be not destroyed, when you change your scene, you have to code this :

void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }

This line of code save your life.

For now, in all scene you will go, this object will remain, and you have a good way to store game information (score, player information, server information,....).

Back to Networking : Client or Server

In ShimNetworkManager, I can test this PLayerOverScene Object to know if I have to run server or client.
public void Start()
    {
         GameObject playerOverScene = GameObject.Find("PlayerOverScene");
        if (playerOverScene == null)
        {
            bool result =this.StartServer();
        }else
        {
            this.StartClient();
        }   
}








Aucun commentaire:

Enregistrer un commentaire