Basic Unity Multiplayer Game With Networker – Part 2

In part 2 of this tutorial we are going to look at loading in settings from a configuration file, and adding logging to our application.

Loading configuration

You can load your configuration any way you want, if you want to use a database for that or an .INI file then go nuts. The recommended way to do configuration is using Microsoft.Extensions.Configuration.

Let’s go ahead and add in the NuGet package which gives us functionality to read configuration from a JSON file.

<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />

Now we need to add our configuration file, so Right click on your .csproj > Add > New Item. Add a text file but call it appSettings.json

Add the following as our default configuration to the appSettings.config

{
  "Networker": {
    "TcpPort": 1000,
    "UdpPort": 1001 
  }
}

Make sure in the file properties you set the file to copy to output directory

Now we need to add the code to read from this file at the top of our Main method

IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", false, true)
    .Build();

Then modify our existing ServerBuilder code to read the TCP and UDP ports from the configuration

var networkerSettings = config.GetSection("Networker");

var server = new ServerBuilder()
    .UseTcp(networkerSettings.GetValue<int>("TcpPort"))
    .UseUdp(networkerSettings.GetValue<int>("UdpPort"))
    .UseProtobufNet()
    .Build();

Logging to console

One of the features of Networker is support for the Microsoft.Extensions.Logging ecosystem.

Let’s go ahead and add in the NuGet package which gives us the functionality to write logs to the console window. Add the following line to our .csproj file.

<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />

Great. So now we have the library imported, but how do we know what type of logs to write? How do we tell Networker to use the console logging?

The first step is to add some new entries into our appSettings.config file.

{
  "Networker": {
    "TcpPort": 1000,
    "UdpPort": 1001
  },
  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    },
    "Console": {
      "LogLevel": {
        "Default": "Debug"
      }
    }
  }
}

Then we tell the ServerBuilder it needs to add logging to console, and we also need to tell it where it can find the settings for that.

var server = new ServerBuilder()
    .UseTcp(networkerSettings.GetValue<int>("TcpPort"))
    .UseUdp(networkerSettings.GetValue<int>("UdpPort"))
    .ConfigureLogging(loggingBuilder =>
    {
        loggingBuilder.AddConfiguration(config.GetSection("Logging"));
        loggingBuilder.AddConsole();
    })
    .UseProtobufNet()
    .Build();

Time to run the project – if you’ve done everything correctly you should see a console that looks something like this

Leave a comment

Your email address will not be published. Required fields are marked *