Skip to content

Unity

AI Summary

A short gist of this page, generated for you.

Powered by AI. Summaries can miss nuance — when in doubt, read the page.

Unity WebGL games talk to the SDK through a small JavaScript plugin (.jslib) and a C# component that wraps it.

You do not add the SDK script tag yourself

When you upload a Unity build in the Developer Portal, Funox replaces the build's index.html with its own page, which already includes the SDK script. Changes made in your own WebGL template are not kept. You only need the two files below.

#Step 1 — The JavaScript plugin

Create Assets/Plugins/WebGL/FunOxSDK.jslib:

javascript
mergeInto(LibraryManager.library, {

  FunOxSDK_Init: function () {
    FunOxSDK.init()
      .then(function (result) {
        SendMessage('FunOxSDKBridge', 'OnSDKReady', JSON.stringify(result));
      })
      .catch(function (error) {
        SendMessage('FunOxSDKBridge', 'OnSDKError', String(error && error.code));
      });
  },

  FunOxSDK_GameplayStart: function () {
    FunOxSDK.gameplayStart();
  },

  FunOxSDK_GameplayStop: function () {
    FunOxSDK.gameplayStop();
  },

  FunOxSDK_HappyTime: function () {
    FunOxSDK.happyTime();
  },

  FunOxSDK_SaveProgress: function (dataJson) {
    var data;
    try {
      data = JSON.parse(UTF8ToString(dataJson));
    } catch (e) {
      SendMessage('FunOxSDKBridge', 'OnSaveError', 'INVALID_DATA');
      return;
    }
    FunOxSDK.saveProgress(data)
      .then(function () {
        SendMessage('FunOxSDKBridge', 'OnSaveSuccess', '');
      })
      .catch(function (err) {
        SendMessage('FunOxSDKBridge', 'OnSaveError', String(err && err.code));
      });
  },

  FunOxSDK_LoadProgress: function () {
    FunOxSDK.loadProgress()
      .then(function (data) {
        SendMessage('FunOxSDKBridge', 'OnLoadSuccess', data ? JSON.stringify(data) : '');
      })
      .catch(function () {
        SendMessage('FunOxSDKBridge', 'OnLoadSuccess', '');
      });
  },

  FunOxSDK_CommercialBreak: function () {
    FunOxSDK.commercialBreak()
      .then(function (result) {
        SendMessage('FunOxSDKBridge', 'OnCommercialBreakDone', JSON.stringify(result));
      })
      .catch(function () {
        // Always answer, so the game is never left paused
        SendMessage('FunOxSDKBridge', 'OnCommercialBreakDone',
          JSON.stringify({ shown: false, completed: false, reason: 'error' }));
      });
  },

  FunOxSDK_RewardedBreak: function (rewardType) {
    FunOxSDK.rewardedBreak(UTF8ToString(rewardType))
      .then(function (result) {
        SendMessage('FunOxSDKBridge', 'OnRewardedBreakDone', JSON.stringify(result));
      })
      .catch(function () {
        SendMessage('FunOxSDKBridge', 'OnRewardedBreakDone',
          JSON.stringify({ shown: false, completed: false, reward: null, reason: 'error' }));
      });
  },

  FunOxSDK_TrackEvent: function (eventName, propertiesJson) {
    var props = {};
    try { props = JSON.parse(UTF8ToString(propertiesJson)); } catch (e) {}
    FunOxSDK.trackEvent(UTF8ToString(eventName), props);
  },

  FunOxSDK_SetupPlatformEvents: function () {
    FunOxSDK.on('pause', function () {
      SendMessage('FunOxSDKBridge', 'OnPlatformPause', '');
    });
    FunOxSDK.on('resume', function () {
      SendMessage('FunOxSDKBridge', 'OnPlatformResume', '');
    });
    FunOxSDK.on('mute', function () {
      SendMessage('FunOxSDKBridge', 'OnPlatformMute', '');
    });
    FunOxSDK.on('unmute', function () {
      SendMessage('FunOxSDKBridge', 'OnPlatformUnmute', '');
    });
    FunOxSDK.on('userChanged', function (data) {
      SendMessage('FunOxSDKBridge', 'OnPlatformUserChanged', JSON.stringify(data));
    });
  }

});

#Step 2 — The C# bridge

Create Assets/Scripts/FunOxSDKBridge.cs:

csharp
using System;
using System.Runtime.InteropServices;
using UnityEngine;

public class FunOxSDKBridge : MonoBehaviour
{
    public static FunOxSDKBridge Instance { get; private set; }

    // Subscribe to these from your game code
    public event Action<string> Ready;               // JSON of the init result
    public event Action Paused;
    public event Action Resumed;
    public event Action Muted;
    public event Action Unmuted;
    public event Action<string> UserChanged;         // JSON: { "user": { ... } } or { "user": null }
    public event Action<string> ProgressLoaded;      // JSON of the save, or "" when there is none
    public event Action ProgressSaved;
    public event Action<string> CommercialBreakDone; // JSON of the ad result
    public event Action<string> RewardedBreakDone;   // JSON of the rewarded ad result

    [DllImport("__Internal")] private static extern void FunOxSDK_Init();
    [DllImport("__Internal")] private static extern void FunOxSDK_GameplayStart();
    [DllImport("__Internal")] private static extern void FunOxSDK_GameplayStop();
    [DllImport("__Internal")] private static extern void FunOxSDK_HappyTime();
    [DllImport("__Internal")] private static extern void FunOxSDK_SaveProgress(string dataJson);
    [DllImport("__Internal")] private static extern void FunOxSDK_LoadProgress();
    [DllImport("__Internal")] private static extern void FunOxSDK_CommercialBreak();
    [DllImport("__Internal")] private static extern void FunOxSDK_RewardedBreak(string rewardType);
    [DllImport("__Internal")] private static extern void FunOxSDK_TrackEvent(string eventName, string propertiesJson);
    [DllImport("__Internal")] private static extern void FunOxSDK_SetupPlatformEvents();

    void Awake()
    {
        if (Instance != null) { Destroy(gameObject); return; }
        Instance = this;
        gameObject.name = "FunOxSDKBridge"; // JavaScript finds this object by name
        DontDestroyOnLoad(gameObject);
    }

    void Start()
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_SetupPlatformEvents();
        FunOxSDK_Init();
#else
        Invoke(nameof(ReportReadyWithoutSdk), 0f); // no SDK in the editor: report ready on the next frame
#endif
    }

    void ReportReadyWithoutSdk() { Ready?.Invoke("{}"); }

    // ── Calls you make ───────────────────────────────────────

    public void GameplayStart()
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_GameplayStart();
#endif
    }

    public void GameplayStop()
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_GameplayStop();
#endif
    }

    public void HappyTime()
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_HappyTime();
#endif
    }

    // data must be a [Serializable] class or struct
    public void SaveProgress(object data)
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_SaveProgress(JsonUtility.ToJson(data));
#endif
    }

    public void LoadProgress()
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_LoadProgress();
#else
        ProgressLoaded?.Invoke("");
#endif
    }

    public void CommercialBreak()
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_CommercialBreak();
#else
        CommercialBreakDone?.Invoke("{\"shown\":false,\"completed\":false}");
#endif
    }

    public void RewardedBreak(string rewardType = "reward")
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_RewardedBreak(rewardType);
#else
        RewardedBreakDone?.Invoke("{\"shown\":false,\"completed\":false}");
#endif
    }

    public void TrackEvent(string eventName, string propertiesJson = "{}")
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        FunOxSDK_TrackEvent(eventName, propertiesJson);
#endif
    }

    // ── Called from JavaScript — do not rename ───────────────

    public void OnSDKReady(string json) { Ready?.Invoke(json); }
    public void OnSDKError(string code) { Debug.LogWarning("Funox SDK error: " + code); Ready?.Invoke("{}"); }
    public void OnPlatformPause(string _) { Paused?.Invoke(); }
    public void OnPlatformResume(string _) { Resumed?.Invoke(); }
    public void OnPlatformMute(string _) { Muted?.Invoke(); }
    public void OnPlatformUnmute(string _) { Unmuted?.Invoke(); }
    public void OnPlatformUserChanged(string json) { UserChanged?.Invoke(json); }
    public void OnSaveSuccess(string _) { ProgressSaved?.Invoke(); }
    public void OnSaveError(string code) { Debug.LogWarning("Funox save error: " + code); }
    public void OnLoadSuccess(string json) { ProgressLoaded?.Invoke(json); }
    public void OnCommercialBreakDone(string json) { CommercialBreakDone?.Invoke(json); }
    public void OnRewardedBreakDone(string json) { RewardedBreakDone?.Invoke(json); }
}

Add an empty GameObject to your first scene and attach FunOxSDKBridge to it. It keeps itself alive across scenes.

#Step 3 — Use it in your game

csharp
using System;
using UnityEngine;

[Serializable]
public class SaveData
{
    public int level;
    public int score;
}

[Serializable]
public class RewardedResult
{
    public bool shown;
    public bool completed;
}

public class GameManager : MonoBehaviour
{
    int currentLevel = 1;
    int score = 0;

    void Start()
    {
        var sdk = FunOxSDKBridge.Instance;
        sdk.Ready += OnSdkReady;
        sdk.ProgressLoaded += OnProgressLoaded;
        sdk.CommercialBreakDone += OnAdBreakDone;
        sdk.RewardedBreakDone += OnRewardedDone;
        sdk.Paused += PauseGame;
        sdk.Resumed += ResumeGame;
        sdk.Muted += MuteAudio;
        sdk.Unmuted += UnmuteAudio;
    }

    void OnSdkReady(string json)
    {
        FunOxSDKBridge.Instance.LoadProgress();
    }

    void OnProgressLoaded(string json)
    {
        if (!string.IsNullOrEmpty(json))
        {
            var save = JsonUtility.FromJson<SaveData>(json);
            currentLevel = save.level;
            score = save.score;
        }
        StartLevel();
    }

    void StartLevel()
    {
        // Active play begins
        FunOxSDKBridge.Instance.GameplayStart();
    }

    void OnLevelComplete()
    {
        var sdk = FunOxSDKBridge.Instance;
        sdk.GameplayStop();
        sdk.SaveProgress(new SaveData { level = currentLevel + 1, score = score });

        // Ad break — pause and mute first
        PauseGame();
        MuteAudio();
        sdk.CommercialBreak();
    }

    void OnAdBreakDone(string json)
    {
        UnmuteAudio();
        ResumeGame();
        currentLevel++;
        StartLevel();
    }

    public void OnWatchAdButton()
    {
        PauseGame();
        MuteAudio();
        FunOxSDKBridge.Instance.RewardedBreak("extra_life");
    }

    void OnRewardedDone(string json)
    {
        UnmuteAudio();
        ResumeGame();
        var result = JsonUtility.FromJson<RewardedResult>(json);
        if (result.completed) GrantExtraLife();
    }

    void GrantExtraLife() { /* your reward */ }

    void PauseGame() { Time.timeScale = 0f; }
    void ResumeGame() { Time.timeScale = 1f; }
    void MuteAudio() { AudioListener.volume = 0f; }
    void UnmuteAudio() { AudioListener.volume = 1f; }
}
Save data must be serializable

JsonUtility only writes [Serializable] classes and structs with public fields. An anonymous object such as new { level = 3 } is saved as an empty {}.

#Uploading

Build for WebGL and upload the whole output folder — the one that contains index.html and the Build folder. Choose Unity as the engine in the upload form.

Test the SDK in the portal preview. A local Build And Run uses Unity's own page, which does not load the SDK, so the plugin's calls fail there.

#Checklist

  • FunOxSDK.jslib is in Assets/Plugins/WebGL/
  • A FunOxSDKBridge object exists in the first scene
  • GameplayStart() is called when a level starts, GameplayStop() when it ends
  • CommercialBreak() is called at a natural break, with the game paused and muted until CommercialBreakDone fires
  • Rewards are granted only when the rewarded result has completed: true
  • All four checks are green in the portal preview