Unity Integration
This guide will walk you through integrating the Funtico SDK into your Unity WebGL game. We’ll cover everything from initial setup to signing in users and saving scores, all with practical code examples.
Prerequisites
Section titled “Prerequisites”Getting Started:
Section titled “Getting Started:”1. Scene Setup
Section titled “1. Scene Setup”Before you can call any SDK functions, you need to add the FunticoManager to your scene. This is a crucial step, as this component handles all the communication with the Funtico backend.
- Create a Manager Object: In your first scene (like a loading or main menu scene), create a new empty GameObject. A good name for it is
FunticoManager. - Add the Script: Attach the
FunticoManager.csscript to the GameObject you just created. - Make it Persistent: The FunticoManager is a singleton that needs to persist across scene loads. The script handles this for you with
DontDestroyOnLoad(gameObject), so you’re all set!
That’s it for the scene setup. Now you can access the SDK from anywhere in your code using FunticoManager.Instance.
2. Setting up the WebGL Template
Section titled “2. Setting up the WebGL Template”Option A: Use Our Pre-configured Template (Recommended)
Section titled “Option A: Use Our Pre-configured Template (Recommended)”The easiest way is to use the template that comes with the Funtico SDK package, which is already set up for you.
- In the Unity Editor, go to Edit > Project Settings > Player.
- Select the WebGL tab.
- Open the Resolution and Presentation section.
- From the WebGL Template dropdown menu, select the Funtico template.
Now, when you build your project, Unity will use this template automatically.
Option B: Modify Your Own Custom Template
Section titled “Option B: Modify Your Own Custom Template”If you are using your own WebGL template, you’ll need to make a few manual edits to your index.html file. These changes are necessary to ensure the Funtico JavaScript SDK (which runs in the browser) can find and communicate with your Unity game instance.
Here are the three required steps:
-
Add the Funtico SDK Script
In the
<head>section of yourindex.html, add the following line to load the Funtico JavaScript library:<script src="https://funtico-frontend-js-sdk.pages.dev/funtico-sdk.min.js"></script> -
Create a Global Instance Variable
The Funtico SDK needs a global variable to find your game. In your
index.html, locate this line:var script = document.createElement("script");Just before it, add the following line to declare the variable:
var myGameInstance = null; -
Assign the Unity Instance
Finally, you need to assign the created Unity game instance to the variable from the previous step. Find the createUnityInstance function call in your file. Inside its .then() block, add myGameInstance = unityInstance;.
It will look like this:
createUnityInstance(canvas, config, (progress) => {//... progress bar logic}).then((unityInstance) => {myGameInstance = unityInstance; // <-- Add this line//... other logic}); -
Add perserving drawing buffer Finally, we need to add one more line, after Unity config creatio. Find definition of config- it will be multiline and will look like this:
var config = { xxx, }Add the following line under it to enable preserving the drawing buffer:config.webglContextAttributes = {"preserveDrawingBuffer": true,"powerPreference": "{{{ WEBGL_POWER_PREFERENCE }}}"};
SDK Usage
Section titled “SDK Usage”Here’s how to use the main features.
1. Initialization
Section titled “1. Initialization”First things first, you need to initialize the SDK. This should be done as early as possible when your game starts.
using FunticoSDK.Runtime.Scripts;using UnityEngine;using Cysharp.Threading.Tasks;
public class GameInitializer : MonoBehaviour{ private string authClientId = "YOUR_CLIENT_ID"; private string env = "production"; // or "sandbox"
void Start() { // Initialize the SDK FunticoManager.Instance.Init(authClientId, env);
// You can then proceed with other logic, like trying to sign the user in CheckUserLoginStatus().Forget(); }
private async UniTaskVoid CheckUserLoginStatus() { //... see next steps }}2. Signing In a User
Section titled “2. Signing In a User”To prompt the user to sign in, you’ll call SignInAsync. Since this is an asynchronous operation, you’ll need to await it.
public async UniTask SignInUser(){ try { Debug.Log("Attempting to sign in..."); await FunticoManager.Instance.SignInAsync(); Debug.Log("Sign-in successful!"); // Now you can load the main game scene or get user info } catch (System.Exception ex) { Debug.LogError($"Sign-in failed: {ex.Message}"); }}3. Getting User Information
Section titled “3. Getting User Information”After a user has signed in, you can retrieve their profile information. The GetUserInfoAsync method returns a FunticoUser object, or null if no user is logged in.
using FunticoSDK.Runtime.Scripts;using UnityEngine;using Cysharp.Threading.Tasks;using UnityEngine.UI; // For Text elements
public class UserProfile : MonoBehaviour{ private Text userNameText; private Text userIDText;
async void Start() { try { FunticoManager.FunticoUser user = await FunticoManager.Instance.GetUserInfoAsync(); if (user!= null) { Debug.Log($"Welcome back, {user.UserName}!"); userNameText.text = user.UserName; userIDText.text = user.UserId; } else { Debug.Log("No user is logged in."); // Maybe show a "Sign In" button here } } catch (System.Exception ex) { Debug.Log($"Could not get user info: {ex.Message}"); } }}4. Saving a Score
Section titled “4. Saving a Score”Saving a player’s score is another simple async call.
public async UniTask SavePlayerScore(int score){ try { Debug.Log($"Saving score: {score}"); string response = await FunticoManager.Instance.SaveScoreAsync(score); Debug.Log($"Server response: {response}"); FunticoManager.ShowAlert("Score saved successfully!"); } catch (System.Exception ex) { Debug.LogError($"Failed to save score: {ex.Message}"); FunticoManager.ShowAlert("Error saving score."); }}5. Signing Out
Section titled “5. Signing Out”To sign the user out, simply call DoSignOut. This is a synchronous call, so no await is needed.
public void LogOut(){ Debug.Log("Signing out..."); FunticoManager.Instance.DoSignOut(); // Return to the main menu or login screen}Editor Mocking
Section titled “Editor Mocking”Building and Running Your WebGL Game
Section titled “Building and Running Your WebGL Game”1. Building the Project
Section titled “1. Building the Project”To create a WebGL build of your game:
- Go to File → Build Settings
- Select WebGL and click “Switch Platform” if it’s not already active
- Click “Build”. Unity will ask you to choose a folder to save the build files
2. Running a Local Server
Section titled “2. Running a Local Server”Here are a few simple ways to start a local server. Open your terminal or command prompt, navigate into your build folder, and run one of the following commands:
Node.js
npx serve -p 3000Python 3
python -m http.server 3000PHP
php -S localhost:3000Then, open your browser to http://localhost:3000.
Best Practices
Section titled “Best Practices”Troubleshooting
Section titled “Troubleshooting”Common Issues and Solutions
Section titled “Common Issues and Solutions”| Issue | Solution |
|---|---|
| ”FunticoManager instance not found” | Ensure FunticoManager GameObject exists in your scene and the script is attached |
| SignInAsync never completes | Check your authClientId is correct and you’re connected to the internet |
| Mock data in WebGL build | Verify the Funtico SDK script is included in your HTML template |
| ”Cannot find myGameInstance” | Follow the Custom HTML Template steps to expose your Unity instance to JavaScript |