How to Setup Vivox with Unity Gaming Services

Want to do more in Vivox?

If you don't understand the code in this tutorial or don't want to implement Vivox from scratch check out my free asset EasyCodeForVivox in the Unity Asset Store (EasyCodeForVivox Does not support Unity Authentication at the moment. You have to input your credentials manually)

Need Help

If you need help with any Vivox related questions, check out the Unity Vivox forums or join the Full Stack Indie Discord and someone from the community will try and help you

Requirements

To follow along in this tutorial, you will need to

  • Have an understanding of event Action<> delegates

  • Create an account with Unity Gaming Services (UGS) and agree with and accept their Terms of Use before you can use their services. UGS may require a credit/debit card to sign up and use their services. You can also create an account with Vivox inside of the Vivox Developer Portal and agree to Vivox’s Terms.

  • Install Vivox inside of the Unity Package Manager or install the Vivox Unity SDK from the Vivox Developer Portal

Vivox supports Unity 2019.4.40f1 (LTS) but Unity recommends using 2020.3 (LTS) versions or higher.

If you decide to install Vivox Unity SDK from the Vivox Developer Portal, you will still need to import these packages from the package manager.

  • com.unity.services.authentication
  • com.unity.settings-manager

You don't have to use these packages, but you are forced to install them so mine as well integrate with UGS Authentication since it is free and helps manage users for you. Vivox uses Settings Manager under the hood to save your credentials and other Vivox related settings found in Edit -> Project Settings -> Services -> Vivox

Unity and Vivox Official Docs

Here is the official Unity and Vivox documentation to help you get your project setup so you can start learning how to implement Vivox

If you decide to use Unity 2019 it is a little more difficult but basically the same process as the tutorials above. It will look a little different though and Unity gives you errors/warnings so you can figure it out. You may have to play the scene a couple times to get Unity to refresh Vivox related settings found in Edit -> Project Settings -> Services -> Vivox

Getting Started

In this tutorial I will using Unity 2021.3.11f1 (LTS) and Vivox from the Unity Package Manager

Make sure TestMode is enabled Project Settings so

TestMode Project Settings.png

Once you have imported the necessary packages create a new C# script. I will call mine VivoxSetup.cs

You do not have to follow my naming conventions on how or what I name things. Follow what convention works for you. It will help you learn better as well by not coping exactly the code that is provided. Change the code to how you would name things and follow best practices. If you look at my older YouTube videos you will see, I didn't follow best practices lol

General Naming Conventions - Framework Design Guidelines | Microsoft Learn

C# Coding Conventions | Microsoft Learn

Initialize Unity Services and Vivox

public class VivoxSetup : MonoBehaviour
{
}

To use Vivox with Unity Authentication & Vivox Services add the following code

private async void Awake()
{
    await UnityServices.InitializeAsync();
    VivoxService.Instance.Initialize();
    VivoxService.Instance.Client.Uninitialize();
    VivoxService.Instance.Client.Initialize();
}
  • Awake method requires async void because Unity Authentication Services use asynchronous programming
  • UnityServices.InitializeAsync() - Sets up all Unity Services with the settings and credentials from Project Settings in your project.
  • VivoxService.Instance.Initialize() - Sets up VivoxService with credentials from UnityAuthentication and Settings from Project Settings
  • VivoxService.Instance.Client.Uninitialize() - Used to make sure Vivox resources are cleaned up if a previous session is still active. Used to prevent errors
  • VivoxService.Instance.Client.Initialize() - Sets up the VivoxUnity.Client to be able to use Vivox Services

Since we have Initialized resources let's make sure those resources are cleaned up when we/players exit our app/game. Add the OnApplicationQuit() method to your class and make sure to Uninitialize the VivoxUnity.Client to prevent memory leaks and make sure we are not being charged for this player session anymore

private void OnApplicationQuit()
    {
        VivoxService.Instance.Client.Uninitialize();
    }

Setup Vivox Configuration

Vivox allows you to pass in extra configuration when Initializing the Client. To start messing around with the different configuration options lets create a setup method

    private VivoxConfig SetupVivoxConfig()
    {
        VivoxConfig vivoxConfig = new VivoxConfig();

        vivoxConfig.MaxLoginsPerUser = 1;
        vivoxConfig.InitialLogLevel = vx_log_level.log_all;

        return vivoxConfig;
    }

We create new VivoxConfig variable, and we set the max logins for a user to 1 (Vivox will count each LoginSession on the same machine as a separate player. If I allow users to have 2 Logins, then it is counted as 2 players(2 PCU's)). We can also set the log level to all to be alerted to what Vivox is doing under the hood. We then return our new VivoxConfig

I don't know too much about the VivoxConfig so check out this Vivox API Doc for more info

We can then add this to our Initialization in the Awake() method and Vivox will use our defined settings

    private async void Awake()
    {
        await UnityServices.InitializeAsync();
        VivoxService.Instance.Initialize();
        VivoxService.Instance.Client.Uninitialize();
        VivoxService.Instance.Client.Initialize(SetupVivoxConfig());
        SubscribeToAuthenticationEvents();
    }

Unity Authentication

Now let's use Unity Authentication to create a session for our Player. We will use the anonymous sign-in option because it is the easiest to use. Add a Start() method to your class

async void Start()
    {
        AuthenticationService.Instance.ClearSessionToken();
        await AuthenticationService.Instance.SignInAnonymouslyAsync();
    }

This method is also async void since async/await (asynchronous programming) is used

  • AuthenticationService.Instance.ClearSessionToken() - Unity will cache/store the token that is created and used when signing in anonymously. This will clear previous caches so when you build your project and have 2 or more instances, they won't conflict with each other.
  • AuthenticationService.Instance.SignInAnonymouslyAsync() - Signs in the player to Unity Authentication Service and manages the player session

Authentication Events

If you were to add your VivoxSetup.cs (or whatever your script is called) to an empty gameobject in your scene and enter play mode you will notice nothing happens and we are not alerted that a Player has logged in. To get notified of Player's signing in we must subscribe to the AuthenticationService events. Create 2 methods called SubscribeToAuthenticationEvents() and UnsubscribeFromAuthenticationEvents()

private void SubscribeToAuthenticationEvents()
{
    AuthenticationService.Instance.SignedIn += OnPlayerSignedIn;
    AuthenticationService.Instance.SignedOut += OnPlayerSignedOut;
    AuthenticationService.Instance.SignInFailed += OnPlayerSignInFailed;
}

private void UnsubscribeFromAuthenticationEvents()
{
    AuthenticationService.Instance.SignedIn -= OnPlayerSignedIn;
    AuthenticationService.Instance.SignedOut -= OnPlayerSignedOut;
    AuthenticationService.Instance.SignInFailed -= OnPlayerSignInFailed;
}

These events are pretty self-explanatory. When a Player is signed in OnPlayerSignedIn() will be called and we can run some code based on this event and so forth for the other events. Let's add the methods that will be called when these events happen (are fired).

private void OnPlayerSignedIn()
    {
        Debug.Log($"Unity has succefully Authenticated Player {AuthenticationService.Instance.PlayerId}");
    }


    private void OnPlayerSignedOut()
    {
        Debug.Log($"Unity has succefully Signed out Player {AuthenticationService.Instance.PlayerId}");
    }


    private void OnPlayerSignInFailed(RequestFailedException request)
    {
        Debug.Log($"Error Authenticating Player : [Message] {request.Message} : [StackTrace] {request.StackTrace}");
   }

These methods are just Debug.Log() statements so we at least know what is going on in your project. Throughout this series we may add more code to these method's. Lets call these methods in the Awake() and OnApplicationQuit() methods.

private async void Awake()
{
    await UnityServices.InitializeAsync();
    VivoxService.Instance.Initialize();
    VivoxService.Instance.Client.Uninitialize();
    VivoxService.Instance.Client.Initialize();

    SubscribeToAuthenticationEvents();
}

private void OnApplicationQuit()
{
    AuthenticationService.Instance.SignOut();
    UnsubscribeFromAuthenticationEvents();
    VivoxService.Instance.Client.Uninitialize();
}
  • We are now subscribing to Authentication events when our script is loaded
  • We are logging out of AuthenticationService before we quit the app
  • We are now Unsubscribing from Authentication events when we quit our app

Now if you run play mode again and check the Unity Console you will see you are notified when a player has successfully signed in. And if you exit play mode you will see the player is signed out.

See the Code

Your script should now look similar to this

That's enough to setup and configuration to start implementing Vivox. In my next post I will show you how to Login to Vivox