Skip to content

unity-banner

PokiSDK - Unity

1. Initialize the SDK

In order to simplify the implementation of our SDK in Unity WebGL games, we’ve created a template and C# class that can be used instead of having to implement the Javascript SDK.

First, make sure to download the required files:

Copy the WebGLTemplates directory from the downloaded zip into your Unity game’s Assets directory.

Now, select the template in Player Settings > WebGL > Resolution and Presentation:

index.html

Our upload system rewrites the contents of index.html. Custom html must be wrapped with <!-- poki include body --> and <!-- poki include end --> Replace ‘body’ with ‘head’ to place the wrapped html in the resulting tag.

Poki Template in Player Settings


Copy the PokiUnitySDK.cs file and the Plugins folder into your project’s Assets folder so you can access the PokiSDK from your code. Now, make sure you initialize the SDK as early as possible in your application by calling PokiUnitySDK.Instance.init();.

Initializing the SDK is not blocking, events will queue up until the SDK is ready. If you want to know when the SDK is ready, you can set a callback function like this:

public void pokiSDKReady(){
    Debug.Log("Poki SDK is ready");
}
PokiUnitySDK.Instance.sdkInitializedCallback = pokiSDKReady;
PokiUnitySDK.Instance.init();


2. Implement the gameplay events

Use the  ðŸŽ® gameplayStart()  event to describe when users are playing your game (e.g. level start and unpause).

Use the  â˜  gameplayStop()  event to describe when users aren’t playing your game (e.g. level finish, game over, pause, quit to menu).

// first level loads, player clicks anywhere
PokiUnitySDK.Instance.gameplayStart();
// player is playing
// player loses round
PokiUnitySDK.Instance.gameplayStop();
// game over screen pops up


3. Implement commercialBreak

Commercial breaks are used to display video ads and should be triggered on natural breaks in your game. Throughout the rest of your game, we recommend you implement the  ðŸŽž commercialBreak()  before every  ðŸŽ® gameplayStart() , i.e. whenever the user has shown an intent to continue playing.

PokiUnitySDK.Instance.commercialBreakCallBack = <function>;
PokiUnitySDK.Instance.commercialBreak();
// <function> is of type Function and will be triggered when the commercial break is finished.
Example:
public void commercialBreakComplete(){
    Debug.Log("Commercial break finished");
}

//Set the complete callback
PokiUnitySDK.Instance.commercialBreakCallBack = commercialBreakComplete;
PokiUnitySDK.Instance.commercialBreak();

Important information about commercialBreaks

Not every single  ðŸŽž commercialBreak()  will trigger an ad. Poki’s system will determine when a user is ready for another ad, so feel free to signal as many commercial break opportunities as possible.


4. Implement rewardedBreak

Rewarded breaks allow for a user to choose to watch a rewarded video ad in exchange for a certain benefit in the game (e.g. more coins, etc.). When using  ðŸŽ¬ rewardedBreak() , please make it clear to the player beforehand that they’re about to watch an ad.

PokiUnitySDK.Instance.rewardedBreakCallBack = <function(withReward)>;
PokiUnitySDK.Instance.rewardedBreak();
// <function> is of type Function and will be triggered when the rewarded break is finished.
Example:
public void rewardedBreakComplete(bool withReward){
    Debug.Log("Rewarded break finished, should i get a reward:"+withReward.ToString());
}

// set the complete callback
PokiUnitySDK.Instance.rewardedBreakCallBack = rewardedBreakComplete;
PokiUnitySDK.Instance.rewardedBreak();

About the rewardedBreak timer

 ðŸŽ¬ rewardedBreak()  affects the timing of  ðŸŽž commercialBreak()  - When a user interacts with a rewarded break, our system’s ad timer is reset to ensure the user does not immediately see another ad.


5. Optimizing your Unity build

Here we have gathered settings, tips, tricks and guides to optimize your Unity build for the web. If you know of more methods to reduce the file sizes or improve performance, let us know!

Build Optimization

Publishing settings

Make sure these settings are implemented in your Unity project before exporting.

  • Set Enable Exceptions to None
  • Set the compression method to Disabled
  • Toggle Name Files As Hashes to ON
  • Read more about these settings here

General

  • Disable any and all built-in Unity modules that your game is not using (such as VR, XR, Terrain etc.)
  • Disable third party plug-ins
  • Toggle Strip Engine Code to ON
  • Set Managed Stripping Level to high (if for some reason it breaks your game set it to medium)
  • Enable Publishing Settings > Data Caching. This allows asset files to be stored to the browser’s local cache, so they don’t need to be re-downloaded.
  • If you’re using the Universal Render Pipeline, disable the post processing as this ads additional size to your build.
  • Compress your Asset Bundles using the LZ4 format. It’s important to not use LZMA compression. You can also leave your asset bundles uncompressed, the Poki server will apply compression for you!

Sounds

  • Try setting audio clips to Mono to see if it greatly reduces the file size.
  • Get rid of redundant audio files if there are any. For example, the audio files with the extension .m4a are not necessary to include in the build, as most browsers accept both .mp3 and .m4a files.
  • Set the Vorbis quality to a value as low as possible, start with 1 and go up in small steps of 5, make the trade-off between quality and size. (hit apply to see filesize effect at the bottom)
  • Large sound files (e.g. music files) might even sound good at 1 Vorbis compressor quality and need compression beyond what Unity can do. What you can do is edit the audio in external audio editor to have 2x pitch, and then set audio source to 0.5 pitch to balance it out - you will have the same audio but as the length is now shorter, it weighs half as much. Quite obviously this results in a decrease in audio quality but it’s very small compared to the filesize improvements you get.
  • Postpone loading music files until the user has interacted with the game. You can achieve this by using Streaming Assets. A good guide on this topic can be found here.

Meshes

  • Set compression to low on meshes and imported animations - this just decreases floating point accuracy so does not hurt quality much but can result in up to 3x filesize reduction for larger meshes.

Textures

For each texture do the following:

  • Set Format to Automatic (default)
  • Set Compression to Low Quality or if the quality is really to low for some assets High Quality
  • Set Use Crunch Compression to a value as low as possible, start with 0 and go up in smalls steps of e.g. 5-10, make the trade-off between quality and size. (hit apply to see filesize effect at the bottom)
  • Make sure to set the Alpha source to None if you don’t need it.
  • Disable mip maps where possible , set filter mode to point and anisoLevel to 1. If your sprites contain gradients, try choosing the options Bilinear or Trilinear.
Pro optimization tips:
  • At the bottom of the texture inspector switch to the WebGL tab and set the format to either DXT1 Crunched or ETC Crunched for non-transparent textures or DXT5 Crunched or ETC2 Crunched for transparent textures. Set the crunch compression quality to lowest possible value where the texture quality still seems acceptable in the preview. Whether DXT or ETC compression methods will yield better results depends on texture, so try both and see which one results in the lower filesize - make sure to hit the apply button to see the effects of the changes.
  • For DXT crunch compression or ETC2, ensure that dimensions are divisible by 4. You need to look not at source dimensions, but at dimensions in Unity asset preview (e.g. if you have a texture which is 2048x2044 but its max size is set to 512, Unity renders it at 512x511, so the height is not divisible by 4 and the compression is not applied correctly despite the setting being set to compressed).
  • For ETC compression, ensure that dimensions are powers of two. Again, need to look at the dimensions in Unity asset preview as the size for the texture in Unity might be set to smaller values.
  • Feel free to refer to our colleague Julien Mourer’s video about reducing asset size:

Also check out Unity’s official guide on optimising your web build here!
And for further even more optimization tips have a look at:
https://www.techarthub.com/an-introduction-to-texture-compression-in-unity/
https://www.techarthub.com/what-is-crunch-compression/

Runtime and performance optimization

  • Make sure that your game objects, particles systems and other game entities are being pooled. That way, they are only created once and don’t get destroyed.
  • Preload game objects that are not used right away manually. Once they are loaded, it can be set to inactive and added to the object pool to be used later.
  • Spread CPU intensive actions over multiple frames. For example when you load a level, it needs to be created over a span of a few frames.
  • Don’t overuse raycasts. If possible, perform a Raycast once every 10 frames.
  • You can improve the visual performance of mobile-compatible builds by uncommenting the line config.devicePixelRatio = 1 directly in the game template.
  • Try to use nested particle systems as sparingly as possible
  • Create an atlas for your UI sprites. This will reduce the number of draw calls so the project will run smoother on the web. Do note, creating atlasses wit transparancy can increase the filesize of your game due to extra white space around the sprites.

Other helpful steps

  • Download the free WebGL Optimizer for Unity. This tool may help you improve your build times and build sizes. P.s. ignore the brotli compression recommendations because Poki handles compression for you.
  • There is a better report tool, but its paid, see Build Report Tool.
  • Another great way to know what takes space in your game is making a build, going to the console, clicking on the top right and selecting Open Editor Log. This will show you a lot of data including the final size of all the assets ordered from largest to smallest.
  • Set API Compatibility Level to .NET 2.0 subset. This has been known to help generate smaller builds.


6. Final steps

Disable sound and input during ads

Make sure that audio and keyboard input are disabled during commercialBreaks, so that the game doesn’t interfere with the ad:

    public void triggerRestartGame() {
        // fire your mute audio function
        // fire your disable keyboard input function
        PokiUnitySDK.Instance.commercialBreakCallBack = restartGame;
        PokiUnitySDK.Instance.commercialBreak();
    }

    public void restartGame(){
        // reset game here
        // fire your unmute audio function
        // fire your enable keyboard input function
    }


Sharable URLs & URL manipulation

You can create and use a sharable url with the following. Use triggerSharableUrl to generate the sharable url. You can receive the url to share in the sharableURLResolved function. Then, use triggerGetUrlParam to retreive the parameters from the url.

PokiUnitySDK.Instance.shareableURLResolvedCallback = shareableURLResolved;
PokiUnitySDK.Instance.shareableURLRejectedCallback = shareableURLRejected;

public class urlParams : ScriptableObject {
    public string param1 = "";
    public string param2 = "";
    public string test3 = "";
}

public void triggerShareableURL(){
    urlParams data = ScriptableObject.CreateInstance<urlParams>();
    data.param1 = "test1";
    data.param2 = "test2";
    data.test3 = "test3";
    PokiUnitySDK.Instance.shareableURL(data);
}

public void shareableURLResolved(string url){
    Debug.Log("shareableURL:"+url);
    debugText.text = "shareableURL:"+url;
}

public void shareableURLRejected(){
    Debug.Log("shareableURL rejected");
    debugText.text = "shareableURL rejected";
}

public void triggerGetURLParam(){
    string identifier = GameObject.Find("displayAd_inputIdentifier").GetComponent<InputField>().text;
    string param = PokiUnitySDK.Instance.getURLParam(identifier);
    Debug.Log("URL param "+identifier+"="+param);
    debugText.text = "URL param "+identifier+"="+param;
}


Images in the Unity loader

To add screenshots of your game to the Unity loader on Poki, you can add up to 4 images to the screenshots folder in your Unity project. They will show up in the loader automatically. You can add 2 sizes per image.

To upload your thumbnail, you can contact us via Discord and we will set this part of the screen up for you!
Screenshots-Unity-loader


Additional helpful methods

Detecting if the SDK is initialized
    PokiUnitySDK.Instance.isInitialized() // returns boolean


Upload and test your game in Poki for Developers

Congrats, you’ve successfully implemented the PokiSDK! Now upload your game to the Poki Inspector and test it there. When you’re happy with the implementation, send us a review request and we’ll play the game. Feel free to contact us via Discord or developersupport@poki.com if you’re stuck.

Export as WASM

Make sure to export your build as a WASM-file. This reduces file-size by +/-30% and increases parsing speed.