DarkRift 2 Tutorial for Unity 3D – Part 5 – Build the server and load game scene

Reminder : You can find all the DarkRift2 related articles here 
You can find the entire project on my official GitHub

Load the game scene

In the last article, we’ve built our server scene. As you surely know, this scene needs to load the shared game scene between the server and the client. So, we just need to include the following namespace in the GameServerManager script :

using UnityEngine.SceneManagement;

and load the scene on the Start() function :

/// Load the game scene
SceneManager.LoadScene("MainGameScene", LoadSceneMode.Additive);

The LoasScene method of the SceneManager takes 2 parameters which are :

  • The name of the scene.
  • The loading mode. If we don’t specify the Additive mode, Unity will remove from the game all opened scenes and load the scene “MainGameScene” alone

It’s not finished, in order to use the correctly the SceneManager, all scenes loaded by this classe need to be added to the build settings. So, follow these steps :

Close the Build Settings window. Let’s run the game. You can see that the MainGameScene is now loaded correctly in the hierarchy.

Build the server

For now, if you have already built games on windows (or another OS), you know that what you see on unity will be displayed on a window on your computer. That’s fine if you need to test your game or build a client version, but for a server, it’s inappropriate.

Yes, the server process doesn’t need to display graphics, play sounds, …, it just needs to handle the game in a background process. Desactivating graphics and sounds for example will reduce the need of resource. By doing that, you will be able to run more servers on the same machine.

Unity provide a “Headless mode” for that. It’s specialy recommended when you build servers.

First step is to add the MainServerScene into the Build Settings. After that, you need to put the server scene at the first place of the build. Like that, when the build will be executed, it will launch the first scene in the Build Settings, to know : MainServerScene :

Select a destination folder for the build, and launch the .exe

Oh damn ! the build seems to execute but throw an exception ! By reading the message, it seems that there is an issue with the DR2 library… the error is :

NotSupportedException: Specified method is not supported.
  at System.Threading.Mutex..ctor (System.Boolean initiallyOwned, System.String name) [0x00006] in <0000d56de0ae43ca875d7babfd990580>:0
  at (wrapper remoting-invoke-with-check) System.Threading.Mutex..ctor(bool,string)
  at DarkRift.Server.DataManager..ctor (DarkRift.Server.DarkRiftServer server, DarkRift.Server.ServerSpawnData+DataSettings settings) [0x0006f] in <56e64ae805e047608792040aeb2db28d>:0
  at DarkRift.Server.DarkRiftServer..ctor (DarkRift.Server.ServerSpawnData spawnData) [0x00024] in <56e64ae805e047608792040aeb2db28d>:0
  at DarkRift.Server.Unity.XmlUnityServer.Create (System.Collections.Specialized.NameValueCollection variables) [0x0007f] in <88a1dbe1fedd44a6993e063fea92a13f>:0
  at DarkRift.Server.Unity.XmlUnityServer.Create () [0x00006] in <88a1dbe1fedd44a6993e063fea92a13f>:0
  at DarkRift.Server.Unity.XmlUnityServer.OnEnable () [0x00008] in <88a1dbe1fedd44a6993e063fea92a13f>:0

Ok, don’t worry, it’s only because the “mutex” class used in DarkRift2 is not compatible with the current “Api Compatibility Level*” parameter. So, open the Build Settings window, and open Player Settings :

Scroll down and change the value to “.NET 4.x” and rebuild the server. Launch it :

Authorize the application to communicate accross the network. And now, you cannot see any error ! Even better, if you read well, you can see a message informing you that the server is listening :

[Info]    DefaultNetworkListener Server mounted, listening on port 4296.

What next ?

On the next article, we will create the client and load the game scene too. It will be relatively simple because it will be extremely closed to what we’ve done in this article. So, if you think that you can do it alone wihtout my help, you can skip the part 6 and go directly to the part 7 !

Thanks you for reading.

DarkRift 2 Tutorial for Unity 3D – Part 4 – Create Unity embedded server

Reminder : You can find all the DarkRift2 related articles here 
You can find the entire project on my official GitHub

Welcome back ! At this point of the tutorial, we are ready to create the unity embedded server. As explained on the last article, we need to create a specific scene for the server. Let’s create the scene named “MainServerScene” :

Create the Unity server

Open the scene

As the scene is created only to host the server process, we don’t need any camera. So delete it. Create a new GameObject in the hierarchy, and name it “GameServerManager“.

Once created, add the “Server” component provided by DarkRift. See the screenshot below :

Be careful of using the right server component, don’t use the Server (Legacy) wich is an old version of the DarkRift server component

Oh, you can see that there is few properties. I will explain them right now !

XML Unity Server properties

  • Configuration : It’s a text asset that the server needs and wich contains the configuration of the server. We’ll take a look on it later.
  • Create on enable : Says to the component that the server creates automatically on startup.
  • Events from dispatcher : DarkRift2 as an internal dispatcher (see more here). Enabling this option allow the server to receive events from the dispacther.
Good to know : The server component is named XML Unity Server only because it is excpecting a configuration file on the XML format !

The configuration file

The configuration file is XML formatted and has the following structure :

  <plugins ></plugins>

As you can see, there is a lot of elements. All are mandatory, except one : <cache>. – See this for reference documentation.

Are you ready to create the configuration file ? No ? Uhhh, ok, by chance, DarkRift provides an example configuration file within the unity package.

You can find it in the following location : DarkRift/DarkRift/Plugins/Server. Drag the file to the component on the GameServerManager :

Now, try to launch the scene, and take a look to the console :

That’s all, the server is mounted and it’s ready to handle client connections and broadcast messages. That’s good but it’s not enough. we need a server manager that will handle clients connections, message broadcasting, ..

So, create folder Scripts/Network and add a new C# script named “GameServerManager“. Add it as component to the GameServerManager game object

The GameServerManager component

For now, we just want that the GameServerManager keep a list of all connected clients. for that we will use a C# List and listen to an event from the XML Unity Server called ClientConnected.

Open the script on Visual Studio or your favorite IDE… wich i hope is Visual Studio 🙂 and copy this code :

/// <summary>
/// List of connected clients
/// </summary>
public List<int> clientsId;

This list need to be initialized before to be used, so in the Start() function, write this :

    private void Start()
        /// Properties initialization
        clientsId = new List<int>();

Now the list is ready to be used, we want to fill it with all the new client who will connect. First thing is to create a property and then get the reference of the XML Unity Server.

using DarkRift.Server.Unity;


    /// <summary>
    /// Reference to the DarkRift server
    /// </summary>
    public XmlUnityServer serverReference;

Don’t forget to reference the DarkRift.Server.Unity namespace ! Then, in the Start() method, use the GetComponent() function :

serverReference = GetComponent<XmlUnityServer>();

Now we have the reference to the DarkRift server, we’ll just suscribe to the event in order to add the client ID to the list. So in the Start() method :

/// Events subscription
serverReference.Server.ClientManager.ClientConnected += ClientConnected;

Finally, create now the ClientConnected callback function :

#region Server events
/// <summary>
/// When a client connects to the DarkRift server
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ClientConnected(object sender, ClientConnectedEventArgs e)

Ok, that’s all. You now know when a client is connected and what is its ID. Good job !

Client disconnection

You can reproduce the same behavior when a client disconnect. Here is the step you need to follow :

  • Suscribe to the ClientDisconnect event
  • Create the ClientDisconnect callback function
  • Remove the ID from the clientsId list

Here is the code

private void Start()
    /// Properties initialization
    clientsId = new List<int>();
    serverReference = GetComponent<XmlUnityServer>();

    /// Events subscription
    serverReference.Server.ClientManager.ClientConnected += ClientConnected;
    serverReference.Server.ClientManager.ClientDisconnected += ClientDisconnected;


/// <summary>
/// When a client disconnects to the DarkRift server
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ClientDisconnected(object sender, ClientDisconnectedEventArgs e)
    throw new NotImplementedException();

I have something to say you…

In fact, you can have at any time the list of all connected clients by using the following code :

//Returns all clients
//Return the first client connected

So, yes, our code is a litte useless now you are aware (JCVD) that you can access these information natively. But later in the tutorial, we’ll use this events to perform additional actions.

In the next article, we’ll load dynamically the MainGameScene and we’ll make a server build of our “game”. Bye !

DarkRift 2 Tutorial for Unity 3D – Part 3 – Architecture and main game scene

Reminder : You can find all the DarkRift2 related articles here 
You can find the entire project on my official GitHub

Unity game architecture with DR2

There are a lots of way to design the game architecture in unity when working in a client/server environnement. It’s very important to think efficiently your architecture, otherwise you can be face of a wall at a certain point of achievement of your project.
In fact, when working with a DR2 unity embedded server, the common difficulty is to keep the scene equal between the server and the client.

For the tutorial, i will use the following implementation :

There are 3 blocks wich represents :

  • Yellow : The server scene
  • Blue : The client scene
  • Green : All the game scene of our project

How they will work together ?

Server Side

When we’ll launch our server, we’ll start the MasterServerScene (wich includes the DR2 server). This scene will load an additive specified scene that contains our game, and that’s all.

Client side

It will be exactly the same way of working

The first advantage of this architecture is that we are sure that the server and the client have the same game scene !

Create the main game scene

First of all, we need to create the main scene of our game. We’ll keep it simple by creating a scene with :

  • A basic platform
  • A bouncing ball (using the Unity 3D physics engine)

Let’s start by creating a simple scene named MainGameScene in the “Scenes” folder

As said, this scene will be shared by both server and client.

Create the platform

Create the platform by right clicking and add a 3D object > Cube

Name it “Platform” and fill the transform with the following values :

Position (0,-4,0) - Scale : (10,1,5)

Create the ball

First thing to make our ball bounce is to create a Physic Material that the “Sphere Collider” will use. So let’s create a new folder named “Physic Materials” and create a new Physic Material

Call it “BouncyBall” and configure it like that

Now, on the scene hierarchy, create a new game object called “BouncyBall

Select the “BouncyBall” object in the scene, and add a Rigidbody component to this object

Finally, we just need to assign the material to the material property within the Sphere Collider component. Go to your Physic Materials folder, and drag the BouncyBall material into the material property of the component.

Ok, if you run the scene, you will see your ball bouncing, but, it’s a little dark, isn’t it ? Let’s polish a little the game. Add a directional light and configure it like that :

And the camera as the screen below :

The result must be something like that :

The bouncing ball that we’ll synchronize with DR2

OK ! Well done, we now have the main scene game ! I totally agree with you, the scene has no interest but it’s an exemple to illustrate how the server will synchronize the bouncing ball with all the connected clients.

Yes, we will synchronize object based on physics ! That’s a good news that i havn’t shared you, isn’t it ? Our server will be authoritative.

Definition : An authoritative server doesn't let the client determines positions, action effect, ... That's the server role. Each synchronized objects are moved, affected, ... on the server. The server then sends data to clients.

On the next article, we’ll setup the ServerMasterScene with DR2.

DarkRift 2 Tutorial for Unity 3D – Part 2 – Get DarkRift2

Reminder : You can find all the DarkRift2 related articles here 
You can find the entire project on my official GitHub

Create an empty scene and download the asset

So, let’s start with a step by step to create the environnement that will be used for the whole entire tutorial.

For this tutorial, i’m using the 2018.3.1f1 version of Unity.

  • Open Unity, and create a new empty project, Go to the asset store, and look for DarkRift2 :

As explainded into my first article , the PRO version is not free, so we’ll use the free version of DR2, wich perfectly fits our needs in this context.

  • Get it, Import it and in the “Import Unity Package” windows, let all checkbox checked :

You can now see in the Asset folder a lot of you content. Let’s describe them just below :

  • DarkRift : Contains a .ZIP wich embbed the .DLL to develop a console server outside Unity. In our case, it will be useless because we’ll make an Unity Embedded Server.
  • 1 ChatDemo, 2 DragDemo, 3BlockDemo : These folders are examples provided by DarkRift. Feel free to open them and take a look. They are very basics, but very instructives too !
  • DarkRift / DarkRift / Plugins : this folder contains all unity components that we need to create our server / client.

DarkRift2 Unity Components

Server side


  • This is THE component that, attached to a GameObject, will act as a server. When attached and game launched, the server will be automatically created and will listen for each connections, messages, … and so on.
Note : UnityServer component is deprecated, don't use it


  • This component is used to create message visible through the console on unity and enable us to debug more easely.


  • Static classes/methods wich are helpers and used by DarkRift2. You can use them too.

Client side


  • As you can see, there is only one unity component for the client : UnityClient. Attacehd to a GameObject, this component will allow you to communicate with a DarkRift2 server.

As the server, the client is automatically created and connects to the server (with a specific [IP:PORT], by default it’s the lookup adress wich is : and port 4296)

What’s next article about ?

The overview of the content of the DR2 asset is finished. The scene to be worked. The next steps are

  • create the scene that will embbed the server
  • Test the server
  • Get output to the console
  • Build our server in both normal & headless mode (Whitout graphics)

Stay connected !

DarkRift 2 Tutorial for Unity 3D – Part 1 – Concepts

DarkRift 2 Tutorial for Unity 3D

What is it ?

Reminder : You can find all the DarkRift2 related articles here 
You can find the entire project on my official GitHub
DarkRift2 (DR2) is an asset developped by “Darkrift” designed to give to your game a multiplayer dimension very easely.

This is the second version of their product, wich is more fast and reliable than the first one. They took the best from DarkRift and they improved it on DarkRift2.

You can find here the website : https://darkriftnetworking.com/DarkRift2

Dark Rift 2 is a librairy wich allow you to send message through network simply and fastly. It’s an abstraction for sending messages over TCP and UDP. It’s a High Level API. It means that you just have to use classes and functions provided in the library to send message. You don’t need to create you TCP message from scratch ! 

DR2 is very interresting regarding it’s price. There is 2 version : 
  • Free : You can use it freely (unlimited users)
  • Pro (90$) : This version provides you some extra feature (Matchmaking, Rooms, ..) and you have a complete access to the source code.
DR2 is extremelly well documented. You can fin all the stuff you need here : 

How to implements Dark Rift ?

There is two way of implementing DR2 with unity.
  1. Using the server console (Provided by Dark Rift)
  2. Using the XML Server Unity Component provided by Dark Rift too…
With the first solution, you’ll need to create your Dark Rift Plugins to handle the server logic. There is a complete exemple on how to create your first plugin with DarkRift. 
The second way is to use the XML Server Unity component on a scene, wich means that a scene will act as server. 
There is pros and cons for each solution. The main pros for using the XML Server Unity is that this component allows us to us the powerful of the Unity engine (Physics, NavPath, …)

Very simple schema of a Dark Rift 2 communication

Here is a very simplified exemple of Client / Server communication. By using Dark Rift, all that is red surrouded is automaticcaly handled by DR2 without doing anything !
In green, that’s what we have to code with DR2 for sending message (You can either receive message, wich is very similar)

For what a message is supposed to be used ?

Message is information shared by a client and a server (for exemple to login) or by all clients (sharing the player position)
A client never send message to another client. It send message to the server, wich broadcast the message to all clients.
As you understood, message are used to share information between connected clients and server act as the broadcaster 
In the next article, we’ll see how to setup the Unity environnement.
Stay tuned !

Create a RPG Battle system with Unity 3D – Part 3 – TurnUnit.cs

In the previous article, we’ve created the turn based battle manager “TurnManager.cs“. The last step is now to create a script that will be attached to an unit. This script will be in charge of starting the turn of the unit.

Unit state

One more time, i will use an enum to handle the unit state. All the explanation is in the as usual :
#region Enum

public enum eTurnUnitState
    INACTIVE,       //The unit is not concerned by the battle right now
    IN_BATTLE,      //Currently in the battle
    SLEEPING        //In the battle, but the timer will not affect the unit



We don’t need so much properties for the TurnUnit.cs component. Let me explain the properties.
  • timeLeftUntilTurnBegin : This is the time the unit need to wait before it’s turn begins
  • originalTurnTime : This is the original time that the unit need to wait AT THE BEGINNING of the battle. Imagine the unit has a speed up power and we need to recover the original turn time, we need to store it.
  • currentTurnTime : This is the time that the unit will wait for the next turn. If the unit has a speed up power, this is that properties that will be modified.
  • state : the current state of the unit
  • turnNumber : store the turn number if needed
#region Properties

/// Time left until the unit turn begin
public float timeLeftUntilTurnBegin;

/// This is the time the unit need to act.
/// More the action time is high, less the unit will act
public float originalTurnTime;

/// current turn time
public float currentTurnTime;

/// State of the unit
public eTurnUnitState state;

/// current turn number
public int turnNumber;


How to notify the TurnManager.cs that a turn starts or ends ? 

The TurnManager will run its timer once the Init() and Run() function are called. But we need to stop the timer when a turn starts. For this, i will use delegates and events. 

Events and delegate

Using events and delegates will make our turn battle system very powerful and usable easely with external components. (I used delegates and not UnityAction. But feel free to replace it with UnityAction if you want)


Simple delegate with one parameter :
#region Delegates
public delegate void TurnUnitEventHandler(TurnUnit pTurnUnit)

Events declaration

I have implemented onUnitTurnStarted and onUnitTurnEnded. You can customize it with more events if you want.
#region Events declaration<br><br>        
    public TurnUnitEventHandler onTurnStarted, onTurnEnded;
    public TurnUnitEventHandler onActionPointAdded, onActionPointConsumed;        #endregion

Trigger events

I always create functions to trigger events. Here is the unity’s implementation :
#region Events

public void OnTurnStarted()
    if (onTurnStarted != null)

public void OnTurnEnded()
    if (onTurnEnded != null)

Initialisation of the TurnUnit.cs component

As you can see, all my scripts have an Init() function. That’s the case for this script too :

/// Use this function to initialize the unit turn
public void Init(
    float pOriginalTurnTime,
    eTurnUnitState pState
    // properties
    originalTurnTime = pOriginalTurnTime;
    currentTurnTime = pOriginalTurnTime;
    state = pState;
    turnNumber = 1;

Remove time from the unit timer

To reduce the wait time before the unit turn begin, we need a function for modifying the property. There is a little subtility. We only remove time if the unit is in the battle 
/// Remove time from the unit turn
public void RemoveTurnTime(float pTime)
    if (state == eTurnUnitState.IN_BATTLE)
        timeLeftUntilTurnBegin -= pTime;

Check if the unit can start its turn

The way to know if a unit can start a turn is very simple. If the property “timeLeftUntilTurnBegin” is lower than 0, it means that the unit can start.

Start and End turns

These functions are simple too but don’t need to forget to trigger events :
/// Use this method to start the turn
public void StartTurn()

    //Trigger event

    //Increase turn number

/// Use this method to end the unit turn
public void EndTurn()
    //Add time for next turn
    timeLeftUntilTurnBegin += currentTurnTime;

    //Trigger event

And that’s all ! We finally created our unit turn based component. In the next article, i will add 1 extra feature : Action Points

These feature are used on tactic game. Our turn battle system can be used on this kind of game too. So it’s interesting to implement it.

Hope you’ve appreciate this article.
Let me know if you have some trouble or if you have some question.

See you soon,

Create a RPG Battle system with Unity 3D – Part 2 – TurnManager.cs

TurnManager.cs : What should it do ?

This script is a component wich will handle all the turn batlle system mechanics. To resume it clearly, it will be in charge of :
  • Time Battle Management : run when no unit is acting, stop when a turn starts et resume when a turn ends.
  • Update elapsed time for all units
  • Start unit turn if is it’s turn
At the end of the tutorial, you will be able to handle battle like this kind of game (I hope you recognized it)
Final fantasy 9 – SquareSoft – 2000


We’ll use an enum for defining the turn manager state as following : 
#region Enums
public enum eTurnManagerState
    NOT_INITIALIZED,    //the turn manager has not been initialized
    INITIALIZED,        //Initialized !
    RUNNING,            //Currently running, no unit is acting
    PAUSED,             //The turn manager is paused, no time is elapsing right now...


For handling all these features, we’ll need all these properties : 
#region Properties

/// List of all units in the battle
private List unitList;

/// State of the turn manager
private eTurnManagerState state;

/// Unit to have to begun its turn
private Queue unitTurnList;

/// Elapsed time since beggining of the battle
private float elapsedTime { get; set;  }

/// Current unit acting
public TurnUnit currentUnitTurn;


I will not define all these properties because it’s cleary named and commented.


To sum up all the needed function for the turn battle manager system :
  • Init : Initialize the component 
  • GetAllUnitInBattle : Get all game objects with a TurnUnit.cs component (will be provided in the next article)
  • UpdateUnitTime : Update Unit elapsed time
  • CheckIfUnitCanStartItsTurn : Check if a unit can start it’s turn, if yes, start the turn !
  • Run : Run the timer
  • Pause : Pause the timer
Here is the Unity’s implementation :
#region Implementation

/// Use this function to initialize the component
public void Init()
    // properties
    unitTurnList = new Queue();
    currentUnitTurn = null;

    state = eTurnManagerState.INITIALIZED;

/// Get All the unit in battle
private void GetAllUnitInBattle()
    unitList = new List();

    foreach(TurnUnit turnUnit in FindObjectsOfType())
        //Suscribe unit events
        turnUnit.onTurnStarted += OnUnitTurnStarted;
        turnUnit.onTurnEnded += OnUnitTurnEnded;

/// Update Unit elapsed time
private void UpdateUnitTime(float pTime)
    foreach(TurnUnit turnUnit in unitList.OrderBy(unit => unit.timeLeftUntilTurnBegin))

        if (turnUnit.CanStartTurn())

/// Check if a unit can start its turn, if yes, start it
public void CheckIfUnitCanStartItsTurn()
    if(unitTurnList.Count > 0)
        currentUnitTurn = unitTurnList.Dequeue();

/// Use this function to start the timer
public void Run()
    state = eTurnManagerState.RUNNING;

/// Use this function to stop the timer
public void Pause()
    state = eTurnManagerState.PAUSED;


Events subscription

As you can see, we’ve suscribded to unit’s events on the GetAllUnitInBattle() function. In fact these event are necessary to : 
  • Pause the timer when the unit begin it’s turn.
  • Resume the timer when the unit has ended its turn
Here is the code of these two function :
#region Events Suscribed

public void OnUnitTurnStarted(TurnUnit pTurnUnit)

public void OnUnitTurnEnded(TurnUnit pTurnUnit)
    currentUnitTurn = null;


Unity callbacks

Now we have all the logic implemented, we can just run the timer in the Unity Update() built-in function as below : 
void Awake()
    state = eTurnManagerState.NOT_INITIALIZED;

void Update()


    if (state == eTurnManagerState.RUNNING)
        this.elapsedTime += Time.deltaTime;
At this point, we have a turn battle system totally functionnal but no unit… Of course, it will be provided to you the in the next article.
It will be a little more complicated, but not so much. Don’t give up !
If you have some review or questions, feel free to post it !
Thanks you for reading. All feedback is appreciated.

Create a RPG battle system with Unity 3D – Part 1 – Concept

Setting up an old school RPG battle system

Nowadays, old J-RPG battle system are not very used, letting the field to mixed action-RPG battle system (FFXV for exemple).

Mechanics used by J-RPG system may seems old, not fun or borring.. but in fact, we can build really great game with some clever ideas… making the game immersive and fun to play. One of the best J-RPG game was without any doubt Final Fantasy 7 developped by the talentuous Squaresoft studio in 1997

Final fantasy 7 – SquareSoft – 1997

Mechanism explanation

What is a J-RPG battle system ? That’s a battle system wich is :

  • Turn based : One unit can act at one time
  • Simple to implement
  • Pleasant to play

3 good reasons to base our new RPG game on this system. For this tutorial, we’ll use Unity 3D 2018. In fact, many of my articles are based on Unity 3D.

No worries, if you are using another game engine (Unreal Engine for exemple…), my articles will be really usefull too..

Next articles

I’ve splitted this course as following :

  1. TurnManager.cs : Implementing the core of the J-RPG battler 
  2. UnitTurn.cs : Implementing unit features as StartTurn(), EndTurn(), … 
  3. Usage example 
Of course, if i found ideas to improve this tutorial, i will implement them and share them with you