How To Send Data From Your Unity App to Google Sheets
In the world of game development and interactive applications, data collection and analysis are crucial. Unity, as one of the most potent game development platforms, allows developers to generate extensive data. But where can this data be analyzed and stored?
One answer is Google Sheets, a collaborative, cloud-based tool with visualization features that can help you make the most of your app's data. In this article, we explore the step-by-step process of sending data from your Unity application to Google Sheets, providing you with a comprehensive guide to streamline your data handling process and enrich your app development journey.
Understanding the basics of Unity and Google Sheets is essential before we dive into the step-by-step guide. So, let's start by learning what Unity and Google Sheets are.
Understanding the Basics of Unity and Google Sheets
What is Unity?
Unity is a powerful game development platform that allows developers to create interactive and immersive experiences. It provides a wide range of tools and features to build apps for various platforms, including mobile devices, desktops, and consoles. Unity uses the C# programming language, making it accessible to developers with different skill levels.
Unity is known for its cross-platform capabilities, enabling developers to build games for more than 25 different platforms including Desktop Platforms (Windows, macOS, Linux), Mobile Platforms (iOS, Android), WebGL, Consoles (PlayStation, Xbox, Nintendo Switch), Virtual Reality (Oculus, HTC Vive, PlayStation VR), and Augmented Reality (ARKit, ARCore).
Unity is a popular choice for game developers due to its ease of use and flexibility. With Unity, developers can create stunning visuals, realistic physics, and engaging gameplay mechanics. The platform offers a visual editor that allows developers to design and build their games without the need for extensive coding knowledge. Additionally, Unity supports third-party integrations, allowing developers to easily incorporate external tools and services into their projects.
What is Google Sheets?
Google Sheets is a versatile, cloud-based spreadsheet software that enables users to create, edit, and collaborate in spreadsheets online. It features a user-friendly interface with robust functionalities such as data validation, formulas, charting options, and an array of templates, catering to various needs like expense tracking or data analysis. Its real-time collaboration feature facilitates simultaneous work in a single spreadsheet by multiple users. The cloud-based nature ensures convenient remote access from any internet-connected device and automatic saving, minimizing data loss risk. Google Sheets also boasts advanced data analysis capabilities with options to apply formulas, create visualizations, and utilize filters and pivot tables. It also supports add-ons for enhanced functionality like advanced data visualization or data import from external sources.
Why integrate Unity with Google Sheets
Sending data from Unity applications to Google Sheets enables you to collect data from your application for the purpose of user attribution, analysis, and sharing of application-generated data, providing critical insights into user behavior and performance metrics. Furthermore, it promotes collaboration in team-based projects due to the easy sharing capabilities of Google Sheets.
This data communication finds practical use in various contexts. For instance, in educational games, it's useful for tracking and assessing student progress. In simulation or training applications, it supports monitoring user interactions and performance evaluation. It also provides a foundation for developing features like leaderboards, achievement tracking, and analytical tools, enhancing overall user engagement and experience.
Setting up your Unity app
Before setting up a Unity app, you might want to get an overview of complete game development workflow.
To build games using Unity, you need to download and install the Unity game engine on your computer. The Unity game engine comes with an editor which allows you to design, develop, and test your games. While Unity does provide SDKs for various platforms like Android, and iOS these SDKs are used to export your Unity projects to these platforms, not to build Unity games directly on these platforms.
Here's a general game development workflow:
1. Develop your game: To develop the game with Unity, you install it on your machine. Unity provides a powerful editor where you can design your game's scenes, create game objects, write scripts, and more.
2. Test your game: Unity allows you to test your game right in the editor. This can be a huge timesaver, as you don't need to deploy your game to your target platform every time you want to test something.
3. Export your game: When you're ready to deploy your game, you can use Unity's build settings to export your game to a variety of platforms. This is where the platform-specific SDKs come into play. For instance, if you're deploying your game to Android, you would need the Android SDK installed on your computer. Unity uses this SDK to create an Android-compatible version of your game.
4. Publish your game: Once you've built your game for your desired platform, you can then further modify the code in platform-specific tools such as Android Studio for Android or xcode for iOS. Once you’re done with the final editing, you can go through the process to publish it, such as submitting it to the Google Play Store for Android games.
Now that you have a high-level overview of game development using Unity, you can go ahead with setting up your first Unity app.
Setting up a Unity project for the first time involves a few steps:
1. Download and Install Unity:
- Go to Unity's download page: https://unity.com/download
- Click on the download link for your operating system and follow the instructions to install Unity.
2. Start Unity and create a new project:
- Open Unity Hub and click on the "New" button.
- Choose a template based on the type of game you want to create. For example, if you're creating a 3D game, choose the 3D template. If you're creating a 2D game, choose the 2D template.
- Name your project and choose a location to save it, then click on the "Create" button.
3. Familiarize yourself with Unity's interface:
- Unity's interface is divided into several windows such as the Scene view, Game view, Hierarchy, Project, and Inspector.
- The Scene view is where you can navigate and edit your game world.
- The Game view is where you can play and test your game.
- The Hierarchy lists all the objects in your current scene.
- The Project window is where all of your game's assets (scripts, models, textures, etc.) are listed.
- The Inspector is where you can view and edit the properties of the currently selected object.
4. Import assets:
- You can import assets (like 3D models, textures, and sounds) into your project by simply dragging them into the Project window.
5. Create your first scene:
- You can create game objects (like cameras, lights, and 3D models) in your scene by going to the "GameObject" menu and choosing the type of object you want to create.
- You can move, rotate, and scale these objects in the Scene view using the transform tools.
6. Write and attach scripts:
There are two key components of Unity scripting you need to understand
- UnityEngine and UnityEditor. UnityEngine is used for the general programming of your game, while UnityEditor is used to create editor scripts that make it easier to develop your game. It's important to remember that UnityEditor should not be used for game logic as it won't be available in your final game build.
- You can write scripts to control the behavior of your game objects by going to the "Assets > Create > C# Script" in the Project window.
- Once you've written a script, you can attach it to a game object by selecting the object in the Hierarchy or Scene view, then dragging the script from the Project window into the Inspector.
7. Build and run your game:
- Once you're happy with your game, you can build and run it by going to the "File > Build Settings" menu, choosing your target platform, and clicking on the "Build And Run" button.
Remember that Unity is a powerful engine with a lot of features, so it may take some time to get comfortable with it. There are plenty of tutorials and resources available on Unity's website and docs to help you get started.
Setting Up Your Google Sheets
To utilize Google Sheets with Unity, first, create a new Google Sheets spreadsheet by navigating to the platform, logging in, clicking "+ New," and choosing "Google Sheets" from the dropdown. Ensure to name the sheet relevantly for easy future access, and customize it using Google Sheets' extensive formatting options. The interface of Google Sheets is user-friendly, offering a toolbar filled with formatting and editing tools for easy data management. The grid-like structure of rows and columns facilitates seamless data entry and manipulation. Further enriching the user experience are features like conditional formatting, data validation, sorting, and filtering which optimize data management and streamline workflow.
A step-by-step guide to sending data from Unity to Google Sheets
In this guide, we will share the steps to send data from Unity to Google Sheets along with code examples. As Unity can build apps for multiple platforms, you can choose to write code to send data from the app in platform-specific code created by Unity, or you can directly write code in Unity. For the purpose of this tutorial, we choose the latter one – writing code directly in Unity.
In this guide, we will share details on how to start by installing any required plugins or libraries that facilitate the communication between Unity and Google Sheets. Next, we will ensure that our Unity app is ready to connect to the internet and authenticate with Google Sheets. Finally, we will identify the data we want to transmit and determine the appropriate format for encoding the information.
Installing dependencies in your Unity app
Unity supports programming with C# programming language. Javascript used to be supported via UnityScript but is now deprecated. In order to interact with Google Sheets from the Unity app, we can either use an HTTP client supported in Unity (e.g. in-built `UnityWebRequest` class) to send requests to Google Sheets API or we can use Google API Client Library for .NET. For the purpose of this tutorial, we will use the .NET Library of Google API Client. Specifically, we will use `Google.Apis.Sheets.v4` and `Google.Apis.Auth` NuGet packages (NuGet is the package manager for .NET).
Because Unity uses a modified version of Mono and .NET, not the standard .NET, the installation is not straightforward as it would have been for .NET projects, you aren’t able to use .NET CLI and install via `dotnet add` command. Instead, follow these instructions:
- Download necessary NuGet packages - Google.Apis.Sheets.v4 and Google.Apis.Auth. After downloading, extract the DLL files from them. As an alternative, if available, you can download the unitypackage files instead.
- Open your Unity project. You can do this via Unity Hub by clicking on the project under the 'Projects' tab.
- Once the project is opened, navigate to the Assets directory in the Project window.
- Right-click inside the Assets directory and select Import New Asset, then Navigate to where you saved your DLL files and import them.
- After importing the DLLs, you need to ensure that they're enabled for your build. To do this, select the DLL in the Project window, then in the Inspector window, ensure that Any Platform and Editor are checked under Select platforms for plugin.
- Depending on the version of Unity and its compatibility with .NET Standard 2.0, you may also need to change your project's API Compatibility Level. You can do this by going to Edit > Project Settings > Player, and under Other Settings > Configuration, change API Compatibility Level to .NET 4.x.
You should now have access to the Google Sheets API classes in your scripts.
Authenticating Google Sheets APIs with your service account credentials
By ensuring that our requests to Google Sheets APIs are authenticated, we will avoid failures in sending data due to a lack of appropriate authentication. There are multiple methods to authenticate Google Sheets API requests, for the purpose of sending data without any user interaction, we need to use service account credentials.
You can get the service account credentials from your Google Cloud Console by following the steps below:
- Go to the Google Cloud Console (console.cloud.google.com).
- Create a new project.
- Enable the Google Sheets API for your project.
- Go to the 'Credentials' section and create new credentials. You'll want to create a service account.
- Download the JSON file that contains your service account keys.
- Keep the JSON file safe - it contains sensitive information that allows access to your Google account.
This credentials JSON file will allow you to authenticate directly from code without requiring any OAuth2 consent screen.
Now, we can go ahead and write a program that authenticates using these credentials. For demo purposes, we will create a spreadsheet. First, we import the dependencies. Then we wrap the task to authenticate service accounts as an `AuthenticateServiceAccount` method which returns a SheetsService instance. We will call this `AuthenticateServiceAccount` and use the returned `SheetsService` instance’s `Spreadsheets.Create` method to create a Google Spreadsheet. This is how your code will look at this point:
CSHARP
using Google.Apis.Auth.OAuth2;using Google.Apis.Sheets.v4;using Google.Apis.Sheets.v4.Data;using Google.Apis.Services;using System.Collections;using System.Collections.Generic;using System.IO;using UnityEngine;public class GoogleSheetsUnity : MonoBehaviour{static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };static readonly string ApplicationName = "Google Sheets API Unity Quickstart";static readonly string SpreadsheetId = "Your SpreadSheet Id";static readonly string sheet = "Sheet1";void Start(){StartCoroutine(AuthenticateAndCreateSpreadsheet());}IEnumerator AuthenticateAndCreateSpreadsheet(){GoogleCredential credential;// Ensure the JSON file is in a location that Unity can access, like StreamingAssets.using (var stream = new FileStream("Assets/StreamingAssets/credentials.json", FileMode.Open, FileAccess.Read)){credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);}// Create the Sheets service.var service = new SheetsService(new BaseClientService.Initializer(){HttpClientInitializer = credential,ApplicationName = ApplicationName,});var spreadsheet = new Spreadsheet(){Properties = new SpreadsheetProperties(){Title = "My new Spreadsheet"}};// Create a new spreadsheetvar spreadsheetCreated = service.Spreadsheets.Create(spreadsheet).Execute();Debug.Log("Spreadsheet ID: " + spreadsheetCreated.SpreadsheetId);yield return null;}}
This script should be attached to a GameObject in the scene. The "credentials.json" should be put into Unity's StreamingAssets folder or another accessible directory and the path adjusted accordingly in the FileStream.
Now that we can send authenticated requests to Google Sheets APIs, we can go ahead and send data to a specific Google Spreadsheet. You can choose to send the data to the spreadsheet we created in this step, or you can choose any other spreadsheet. If you choose any other spreadsheet, make sure that it is shared with the service account client email so that it has access to update it.
In the next section, we'll discuss how to send data from your application to your Google Sheets in real-time.
Sending data from Unity app to Google Sheets
Sending real-time data to Google Sheets means we need to continuously update Google Sheets from the Unity app by sending API requests to update a particular spreadsheet.
To do this, we are going to create a method to `UpdateValues` using SheetService instance’s `Spreadsheets.Values.Update` method. Then we can use this method wherever we need to update the spreadsheet values.
CSHARP
using Google.Apis.Auth.OAuth2;using Google.Apis.Sheets.v4;using Google.Apis.Sheets.v4.Data;using Google.Apis.Services;using System.Collections;using System.Collections.Generic;using System.IO;using UnityEngine;using UnityEngine.Networking;public class GoogleSheetsExample : MonoBehaviour{static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };static readonly string ApplicationName = "Google Sheets API .NET Quickstart";static readonly string SpreadsheetId = "Your SpreadSheet Id";static readonly string sheet = "Sheet1";private void Start(){StartCoroutine(AuthenticateAndCreateSpreadsheet());}IEnumerator AuthenticateAndCreateSpreadsheet(){GoogleCredential credential;// Put the name of your service account credential file in place of 'credentials.json'using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)){credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);}// Create the Sheets service.var service = new SheetsService(new BaseClientService.Initializer(){HttpClientInitializer = credential,ApplicationName = ApplicationName,});var spreadsheet = new Spreadsheet(){Properties = new SpreadsheetProperties(){Title = "My new Spreadsheet"}};// Create a new spreadsheetvar spreadsheetCreated = service.Spreadsheets.Create(spreadsheet).Execute();Debug.Log("Spreadsheet ID: " + spreadsheetCreated.SpreadsheetId);// Update valuesvar range = "Sheet1!A1";var values = new List<IList<object>> { new List<object> { "Hello, Google Sheets!" } };// Call the UpdateValues Coroutineyield return StartCoroutine(UpdateValues(service, spreadsheetCreated.SpreadsheetId, range, values));}IEnumerator UpdateValues(SheetsService service, string spreadsheetId, string range, IList<IList<object>> values){ValueRange body = new ValueRange{Values = values};var update = service.Spreadsheets.Values.Update(body, spreadsheetId, range);update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;yield return update.Execute();Debug.Log($"{update.UpdatedCells} cells updated.");}}
That’s it! Now you can send data from the Unity app to Google Sheets.
Conclusion
With this step-by-step guide, you should now have a clear understanding of how to send data from your Unity app to Google Sheets. Remember to adapt the instructions to meet your specific project requirements and explore additional resources and tutorials for further enhancing your integration. By leveraging the power of Unity and Google Sheets, you can collect, analyze, and utilize your app's data effectively. Happy coding! Don't want to go through the pain of direct integration? RudderStack’s Unity App to Google Sheets integration makes it easy to send data from X to Y.