How to Setup Vivox from Scratch

Table of contents

No heading

No headings in the article.



### Want to do more with 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](https://assetstore.unity.com/packages/add-ons/easycodeforvivox-202190) 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](https://forum.unity.com/forums/vivox-voice-text-chat.737/) or join the [Full Stack Indie Discord](https://discord.gg/Kh5tt5yHcF) 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 may 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 if you are forced to install them, mine as well integrate with **UGS Authentication** since it is free and helps manage users for you. Check out my [blog series](https://blog.fullstackindie.net/series/vivox-with-unity-services) on how to use Vivox with Unity Services

### Official Unity and Vivox 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 from scratch

- [Get started with Vivox in my Unity Project](https://support.unity.com/hc/en-us/articles/6380084154772-Vivox-How-do-I-get-started-with-Vivox-in-my-Unity-Project-)

- [Vivox Unity SDK QuickStart](https://docs.unity3d.com/Packages/com.unity.services.vivox@15.1/manual/index.html#set-upinitialize)

- [Vivox Developer Portal Walkthrough](https://support.unity.com/hc/en-us/articles/4433368681108-Vivox-Developer-Portal-Walkthrough)

- [Create a Project and get Credentials](https://support.unity.com/hc/en-us/articles/4433401448852)

> If you decide to use **Unity 2019 it is a little more difficult**(I don't recommend it) 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

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](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions)

[C# Coding Conventions | Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions)

```
public class VivoxSetup : MonoBehaviour
{
}
```
To setup the VivoxUnity.Client add the following code
```
    public VivoxUnity.Client Client { get; private set; }

    private void Awake()
    {
        Client = new VivoxUnity.Client();
    }
```
- We create a [Property](https://learn.microsoft.com/en-us/dotnet/csharp/properties) to hold the instance of the **VivoxUnity.Client**. We have a public get so it can be accessed from other classes and a private set so it can only set/changed in the VivoxSetup class.
- Awake method creates an instance of the Client

## Things to Consider
**There should only be 1 instance of the VivoxUnity.Client** throughout the lifetime of your project. To achieve the result there are a few different ways to do so.

- You can use **DontDestroyOnLoad(this);** in the awake method so this class is never destroyed

- You can make **Client** a static property ```
public static VivoxUnity.Client Client;
``` so there will only ever be one instance and then Client can be accessed from any class

- You can create a [Singleton ](https://gamedevbeginner.com/singletons-in-unity-the-right-way/#:~:text=What%20is%20a%20singleton%20in%20Unity%3F%20Generally%20speaking%2C,to%20the%20player%20or%20to%20other%20game%20systems.) (Which is basically just a static instance of the whole class vs just the Client property). The examples shown in the [John's blog](https://gamedevbeginner.com/singletons-in-unity-the-right-way/#:~:text=A%20singleton%20in%20Unity%20is%20a%20normal%20class,an%20instance%20of%20its%20own%20type.%20Like%20this%3A)  do not handle multithreading scenarios. Check out [this blog by Jon Skeet](https://csharpindepth.com/articles/Singleton) for more info

- You can use dependency injection framework like **Zenject** to pass existing instances of Client to another class without having to use static properties/variables, Singleton pattern in Unity (Dependency Injection is technically a singleton pattern), or having to use DontDestroyOnLoad(this);

**All these options have their pro's and con's and are out of the scope of this tutorial so do your own research.  Just something to think about when dealing with objects that only ever need 1 instance per scene/game session**. I am going to make Client a public static Property for ease of use in my future tutorials

## Initialize VivoxClient
Now let's Initialize our Client. Add a **Start()** method to your class
```
async void Start()
    {
        if (!Client.Initialized)
        {
            Client.Uninitialize();
            Client.Initialize();
        }
        else
        {
            Debug.Log("Vivox Client is already Initialized. Skipping...");
        }
    }
```
This method is checks to see if we have Initialized the **VivoxClient** already. 
- If we haven't, we **Uninitialize()** first to make sure previous sessions are properly cleaned up in the event there was an error when we closed the game/app last time. 
- We then **Initialize()** the Vivox Client so we can start accessing Vivox Server's and resources and display a console message alerting that Vivox is Initialized

If the **Client** was initialized already, we just write a console message alerting us an attempt was made to re-initialize the Client. This can be helpful if there are errors using Vivox when changing scenes. This can help us narrow down where we need to start checking for errors

### Cleaning Up Vivox Resources
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()
    {
        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](https://docs.vivox.com/v5/general/unity/15_1_190000/en-us/Default.htm#ReferenceManual/Unity/class_vivox_unity_1_1_vivox_config.html%3FTocPath%3DCore%7CUnity%2520API%2520Reference%2520Manual%7CUnity%20API%20Reference%20Manual%7CClass%20List%7C_____22) for more info

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

```
    private void Start()
    {
        if (!Client.Initialized)
        {
            Client.Uninitialize();
            Client.Initialize(SetupVivoxConfig()); 
            Debug.Log("Vivox Client is Initialized.");
        }
        else
        {
            Debug.Log("Vivox Client is already Initialized. Skipping...");
        }
    }
```

## **See the Code**

Your script should now look similar to this

%[https://gist.github.com/FullStackIndie/f93eafe3cd99e3f7cefa5d9e0431f2c4]

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