# Unity SDK v2

See the [GitHub codebase](https://github.com/rudderlabs/rudder-sdk-unity-v2) to get a more hands-on understanding of the SDK.

## SDK setup requirements

- Download and install the [Unity development kit](https://store.unity.com/download).
- Sign up for [RudderStack](https://app.rudderstack.com/signup).
- [Set up a Unity source]({{< ref "dashboard-guides/sources/_index.md#adding-a-source" >}}) in your [RudderStack dashboard](https://app.rudderstack.com/). Note the {{< glossary_tooltip "write-key" >}} for this source.
- You will also need the [data plane URL]({{< ref "dashboard-guides/_index.md#connections" >}}) associated with your RudderStack workspace.

## Installing the Unity SDK

1. [Download](https://github.com/rudderlabs/rudder-sdk-unity-v2/releases) `rudder-sdk-unity.unitypackage`.
2. Import the downloaded package to your project. From the **Assets** menu, go to **Import Package**  > **Custom Package...** :

{{< image src="images/event-stream-sources/unity-sdk-installation-1.webp" alt="Import custom package" >}}

3. Select `rudder-sdk-unity.unitypackage` from the downloaded location and click **Open**:

{{< image src="images/event-stream-sources/unity-sdk-installation-2.webp" alt="Select RudderStack Unity package" >}}

4. Click **Import** in the import popup:

{{< image src="images/event-stream-sources/unity-sdk-installation-3-new.webp" alt="Import popup" >}}

5. Add the **RudderStack.prefab** file from the path `Assets/RudderStack/Unity/Prefabs/RudderStack.prefab` to every scene in your Unity app. Also, make sure that `RudderStack.prefab` is linked to the `RSMaster`, `RSScreenView`, and `RSLogger` scripts.

{{< image src="images/event-stream-sources/unity-sdk-installation-4-new.webp" alt="Add prefab file" >}}

## Initializing the RudderStack client

1. Import the SDK:

```csharp
using RudderStack.Unity;
```

2. Initialize the SDK as shown. Replace `WRITE_KEY` and `DATA_PLANE_URL` with the actual values obtained in the [SDK setup requirements](#sdk-setup-requirements) section.

```csharp
RSAnalytics.Initialize("WRITE_KEY",
		new RSConfig(dataPlaneUrl: "DATA_PLANE_URL"));

// for coroutine
StartCoroutine(RSAnalytics.InitializeRoutine("WRITE_KEY",
		new RSConfig(dataPlaneUrl: "DATA_PLANE_URL")));
```

## SDK initialization options

You can configure your client based on the following parameters using `RudderConfigBuilder`:

| Parameter | Type | Description | 
| :---------- | :-------- | :-------------- |
| `logLevel`              | Enum     | Controls how much of the log you want to see from the SDK. <br /><br />**Default value**: `Logger.Level.INFO` |
| `dataPlaneUrl`          | String  | Your data plane URL. |
| `dbThresholdCount`      | Integer     | Number of events to be saved in the `SQLite` database. Once the limit is reached, older events are deleted from the database. <br /><br />**Default value**: `10000` |
| `sleepcount` | Integer     | Minimum waiting time to flush the events to the RudderStack server. The minimum value can be set to `1 second`.<br /><br />**Default value**:`10 seconds` |
| `trackLifecycleEvents`  | Boolean | Determines if the SDK will automatically capture the application lifecycle events. <br /><br />**Default value**: `true` |
| `recordScreenViews`     | Boolean | Determines if the SDK will automatically capture the screen view events. <br /><br />**Default value**: `false` |
| `controlPlaneUrl`       | String  | Change this parameter **only if** you are self-hosting the control plane. Check the [Self-hosted control plane](#self-hosted-control-plane) section below for more information. The SDK will add `/sourceConfig` along with this URL to fetch the source configuration.<br /><br />**Default value**: `https://api.rudderlabs.com` |
| `gzip` | Boolean | Gzips the event requests. <br /><br /> **Default value**: `true` |

### Self-hosted control plane

Do not pass the `controlPlaneUrl` parameter during the SDK initialization if you are using the [RudderStack dashboard](https://app.rudderstack.com) to set up your connections. The SDK supports this parameter only if you are using the open source [Control Plane Lite](https://github.com/rudderlabs/config-generator#rudderstack-control-plane-lite) utility to self-host your control plane.

## Identify

The [`identify`]({{< ref "event-spec/standard-events/identify.md" >}}) call lets you identify a visiting user and associate them to their actions. It also lets you record the traits about them like their name, email address, etc.

The Unity SDK captures `deviceId` and uses that as `anonymousId` for identifying the user. This helps in tracking the users across the application installation. To attach more information to the user, use the `identify` method. 

Once the SDK identifies the user, the SDK persists and passes the user information to the subsequent calls. To reset the user identification, use the [`reset`](#reset) method.

The following snippet highlights a sample `identify` call:

```csharp
RSAnalytics.Client.Identify("unity_user_id",
                new Dictionary<string, object> { { "email", "abc@example.com" }, { "age", 24 }, { "name", "First Last" }, { "gender", "Male" } });
```

### Override `anonymousId` using `setAnonymousId`

You can explicitly set the `anonymousId` for all future events using the `PutAnonymousId()` method.

 ```csharp
RSClient.PutAnonymousId("anonymous_id");
 ```

## Track

The [`track`]({{< ref "event-spec/standard-events/track.md" >}}) call lets you record the users' in-game activity. Each user action is called an **event**.

The following snippet highlights a sample `track` call:

```csharp
RSAnalytics.Client.Track("sample_track",
                new Dictionary<string, object> { { "key_1", "value_1" }, { "key_2", 4 }, { "key_3", 4.2 }, { "key_4", true } });
```

### Track application lifecycle events

The Unity SDK lets you track the [Application Lifecycle Events]({{< ref "event-spec/standard-events/application-lifecycle-events-spec.md" >}}) to get insights into the app metrics like installs, opens, updates, etc. 

To enable automatic tracking, set `trackLifeCycleEvents` method to `true` while initializing the SDK:

```csharp
RSAnalytics.Initialize("WRITE_KEY",
                new RSConfig(dataPlaneUrl: "DATA_PLANE_URL")
                    .SetTrackLifeCycleEvents(true));
```

### Trigger Application Updated lifecycle event

To ensure that the **Application Updated** lifecycle event is triggered successfully:

- **For iOS**: Make sure the `Bundle version` in the `Info.plist` file of your application is incremented. If the `Bundle version` of your `target` points to the `Bundle version` of your `project`, then increment it.
- **For Android**: Make sure the `versionCode` in the `defaultConfig` object nested in the `android` object of your app's `build.gradle` is incremented.

Refer to the [Application Lifecycle Events Specification]({{< ref "event-spec/standard-events/application-lifecycle-events-spec.md#application-updated" >}}) guide for more information.

## Screen

The [`screen`]({{< ref "event-spec/standard-events/screen.md" >}}) call is the mobile equivalent of the [`page`]({{< ref "event-spec/standard-events/page.md" >}}) call. It lets you record the screen views on your mobile app along with other relevant information about the screen.

The following snippet highlights a sample `screen` call:

```csharp
RSAnalytics.Client.Screen("sample_screen",
                new Dictionary<string, object> { { "key_1", "value_1" }, { "key_2", 4 }, { "key_3", 4.2 }, { "key_4", true } });
```

### Automatic screen recording

You can enable the automatic recording of screen views by setting `recordScreenViews` to `true` while initializing the SDK. This automatically sends a `screen` call for every screen that a user views. By default, `recordScreenViews` is set to `false`.

```csharp
RSAnalytics.Initialize("WRITE_KEY",
                new RSConfig(dataPlaneUrl: "DATA_PLANE_URL")
                    .SetRecordScreenViews(true));
```

{{< info >}}
The `recordScreenViews` parameter records the screen views of the native Android [Activities](https://developer.android.com/guide/components/activities/intro-activities) or the iOS [Views](https://developer.apple.com/documentation/uikit/view_controllers) only and **not** by the React Native Views.
{{< /info >}}

## Page

The [`page`]({{< ref "event-spec/standard-events/page.md" >}}) call lets you record the page views on your application along with the other relevant information about the page.

A sample `page` call is shown below:

```csharp
RSAnalytics.Client.Page("sample_page",
                new Dictionary<string, object> { { "key_1", "value_1" }, { "key_2", 4 }, { "key_3", 4.2 }, { "key_4", true } });
```

## Group

The [`group`]({{< ref "event-spec/standard-events/group.md" >}}) call lets you link an identified user with a group, such as a company, organization, or an account. It also lets you record any custom traits or properties associated with that group.

The following snippet highlights a sample `group` call made using the Unity SDK:

```csharp
RSAnalytics.Client.Group("group_id",
                new Dictionary<string, object> { { "key_1", "value_1" }, { "key_2", 4 }, { "key_3", 4.2 }, { "key_4", true } });
```

## Alias

The [`alias`]({{< ref "event-spec/standard-events/alias.md" >}}) call lets you merge different identities of a known user. It is an advanced method that lets you change the tracked user's ID explicitly. You can use `alias` for managing the user's identity in some of the downstream destinations.

{{< warning >}}
RudderStack supports sending `alias` events only to select downstream destinations. Refer to the [destination-specific documentation]({{< ref "destinations/streaming-destinations/_index.md" >}}) for more details.
{{< /warning >}}

A sample `alias` call is shown below:

```csharp
RSAnalytics.Client.Alias("new_unity_user_id");
```

## Reset

The `reset` method clears all persisted traits of the previously identified user.

```csharp
RSAnalytics.Client.Reset();
```

## Set the advertisement ID

Use the `PutAdvertisingId()` method to explicitly set an advertising ID.

```csharp
RSClient.PutAdvertisingId("advertisement_id");
```

## Set the device token

You can pass your device token for push notifications for the destinations which support the feature using the `PutDeviceToken()` method. RudderStack sets the token under `context.device.token`.

```csharp
RSClient.PutDeviceToken("device_token");
```

## FAQ

#### Which platforms are does Unity SDK support?

The Unity SDK v2 supports the following platforms:

- Android
- iOS
- Windows
- macOS
- Xbox
- PlayStation

#### Do I need to add anything to my Android ProGuard rules?

If you are facing any event delivery issues in your production environment, verify if you have added the following line in your ProGuard rules:

```java
-keep class com.rudderstack.android.** { *; }
```

#### How do I gzip event requests in Unity SDK?

The Unity SDK automatically gzips requests. To disable this feature, set the `Gzip` parameter to `false` while initializing the SDK:

```csharp
RSAnalytics.Initialize("WRITE_KEY",
                new RSConfig(dataPlaneUrl: "DATA_PLANE_URL")
                    .SetGzip(false));
```

{{< warning >}}
Gzip requires [rudder-server](https://github.com/rudderlabs/rudder-server) **v1.4 or higher**. Otherwise, your events might fail.
{{< /warning >}}
