meta-instant-games-unity-plugin

Meta Instant Games Unity Plugin - API Reference

A Unity plugin that wraps the Facebook Instant Games SDK, enabling Unity WebGL games to access platform features such as player identity, social contexts, payments, tournaments, ads, and overlay views.


Table of Contents


Getting Started

Requirements

Project Setup

  1. Import the plugin into your Unity project under Assets/Meta.InstantGames/.
  2. Open Window > Instant Games > Project Optimiser to apply recommended WebGL build settings:
    • Build target: WebGL
    • Compression: Disabled
    • WebGL template: PROJECT:FB
    • Run In Background: Enabled
    • Input Handling: Both
  3. Use the WebGL template at Assets/WebGLTemplates/FB/ which handles SDK initialization automatically.

Basic Usage

using Meta.InstantGames;

// Initialize
await FBInstant.InitializeAsync();
await FBInstant.StartGameAsync();

// Get player info
string playerId = await FBInstant.Player.GetID();

// Post a score
await FBInstant.PostSessionScore(100);

All API calls are async and return Task<string> or typed results. In the Unity Editor, calls return mock data after a short delay for testing purposes.


Architecture

Plugin Structure

Assets/Meta.InstantGames/
  Editor/        - Editor windows (bundle uploader, overlay builder)
  Runtime/
    Plugins/     - FBInstant API wrappers + JS interop files
      UtilClasses/ - Data models, enums, payload types
    Scripts/     - Bridge, JSON utilities, demo components

Assemblies

Assembly Scope Description
Meta.InstantGames.Runtime Editor + WebGL Core runtime API
Meta.InstantGames.Editor Editor only Editor tools
Meta.InstantGames.Tests Tests Runtime unit tests
Meta.InstantGames.Editor.Tests Tests Editor unit tests

Key Patterns


Core API

All core API classes are in the Meta.InstantGames namespace.

FBInstant

The central entry point. Access sub-APIs via static properties.

Namespace: Meta.InstantGames

Static Properties

Property Type Description
Instance FBInstant Singleton instance
Player Player Player sub-API
Context Context Context sub-API
Payment Payment Payment sub-API
Tournament Tournament Tournament sub-API
Community Community Community sub-API
Room Room Room sub-API
OverlayViews OverlayViews Overlay views sub-API

Lifecycle Methods

Method Returns Description
InitializeAsync() Task<string> Initialize the SDK
StartGameAsync() Task<string> Signal the game is ready
SetLoadingProgress(int progress) Task<string> Set loading bar (0-100)
Quit() void Quit the game

Platform Methods

Method Returns Description
GetLocale() Task<string> User’s locale string
GetPlatform() Task<string> Platform (IOS/ANDROID/WEB/MOBILE_WEB)
GetSDKVersion() Task<string> SDK version string
GetSupportedAPIs() Task<string> List of supported APIs
GetEntryPointData() Task<string> Data passed from entry point
GetEntryPointAsync() Task<string> Entry point name

Social Methods

Method Returns Description
ShareAsync(ShareWithOverlayPayload) Task<string> Open share dialog
InviteAsync(InviteWithOverlayPayload) Task<string> Open invite dialog
UpdateAsync(CustomUpdateWithOverlayPayload) Task<string> Send a custom update to context
SwitchGameAsync(string gameId, string data) Task<string> Switch to another instant game

Score & Session Methods

Method Returns Description
PostSessionScore(int score) Task<string> Post a session score
PostSessionScoreAsync(int score) Task<string> Post a session score (async variant)
SetSessionData(string sessionData) Task<string> Set session data (JSON string)
LogEvent(string name, string value, string data) Task<string> Log an analytics event

Shortcut Methods

Method Returns Description
CanCreateShortcutAsync() Task<string> Check if shortcut creation is available
CreateShortcutAsync() Task<string> Create a home screen shortcut

Ad Methods

Method Returns Description
GetInterstitialAdAsync(string placementID) Task<AdInstance> Create an interstitial ad
GetRewardedVideoAsync(string placementID) Task<AdInstance> Create a rewarded video ad
GetRewardedInterstitialAsync(string placementID) Task<AdInstance> Create a rewarded interstitial ad
LoadBannerAdAsync(string bannerId, string position) Task<string> Load a banner ad
HideBannerAdAsync() Task<string> Hide the banner ad

Matchmaking Methods

Method Returns Description
CheckCanPlayerMatchAsync() Task<string> Check if matchmaking is available
MatchPlayerAsync(string tag, bool switchContext, bool offline) Task<string> Match with another player

Miscellaneous Methods

Method Returns Description
GetTournamentAsync() Task<TournamentInstance> Get current tournament
PerformHapticFeedbackAsync() Task<string> Trigger haptic feedback
GetScreenshot() Task<string> Capture canvas screenshot (base64)
GetCanvasRect() Task<string> Get canvas DOM bounding rect

Event Handlers

Method Parameters Description
OnPause(Action<string>) Callback Register for pause events
OnContextChange(Action<string>, Action<string>) Success, Error callbacks Register for context change events

Player

Access via FBInstant.Player.

Method Returns Description
GetID() Task<string> Player’s unique ID
GetASIDAsync() Task<string> App-scoped user ID
GetSignedASIDAsync() Task<SignedASID> Signed app-scoped user ID
GetSignedPlayerInfoAsync() Task<SignedPlayerInfo> Signed player info with verification
CanSubscribeBotAsync() Task<string> Check bot subscription availability
IsSubscribedBotAsync() Task<string> Check if subscribed to bot
SubscribeBotAsync() Task<string> Subscribe to game bot
GetDataAsync(string[] keys) Task<string> Get player data for specified keys
SetDataAsync(string data) Task<string> Set player data (JSON string)
FlushDataAsync() Task<string> Flush pending data writes
GetConnectedPlayersAsync() Task<ConnectedPlayer[]> Get connected players

Context

Access via FBInstant.Context.

Method Returns Description
GetID() Task<string> Current context ID
SwitchAsync(string id, bool switchSilently) Task Switch to a different context
CreateAsync(string[] playerIds) Task<string> Create a new context (empty array opens selection dialog)
GetPlayersAsync() Task<ContextPlayer[]> Get players in the current context
ChooseAsync() Task Open context selection dialog

Payment

Access via FBInstant.Payment.

Method Returns Description
GetCatalogAsync() Task<Product[]> Get product catalog
PurchaseAsync(PurchaseConfig config) Task<string> Purchase a product
GetPurchasesAsync() Task<string> Get unconsumed purchases
ConsumePurchaseAsync(string productId) Task<string> Consume a purchase
OnReady(Action<string> callback) void Register callback for payment readiness

Tournament

Access via FBInstant.Tournament.

Method Returns Description
CreateAsync(int score, CreateTournamentConfig config, Json data) Task<string> Create a tournament
GetTournamentsAsync() Task<TournamentInstance[]> Get available tournaments
JoinAsync(string tournamentId) Task<string> Join a tournament
PostScoreAsync(int score) Task<string> Post score to current tournament
ShareAsync(ShareTournamentPayload payload) Task<string> Share a tournament

Community

Access via FBInstant.Community.

Method Returns Description
CanFollowOfficialPageAsync() Task<string> Check if player can follow page
CanJoinOfficialGroupAsync() Task<string> Check if player can join group
FollowOfficialPageAsync() Task Follow the official page
JoinOfficialGroupAsync() Task Join the official group

Room

Access via FBInstant.Room.

Method Returns Description
GetCurrentMatchAsync() Task<string> Get current match data

Overlay Views

Overlay views are HTML/CSS layers rendered on top of the Unity WebGL canvas. They support templating, data binding, and custom events.

OverlayViews

Factory and manager for overlay views. Access via FBInstant.OverlayViews.

Fields

Field Type Description
overlayViewList List<OverlayView> All tracked overlay views

Creation Methods

Method Returns Description
CreateOverlayView(path, css, data, onLoad, onError) Task<OverlayView> Create from XML file path with callbacks
CreateOverlayViewAsync(path, domId, style, css, data) Task<OverlayView> Create from XML file attached to DOM element
CreateOverlayViewWithXMLString(xml, css, data, onLoad, onError, basePath) Task<OverlayView> Create from inline XML with callbacks
CreateOverlayViewWithXMLStringAsync(xml, domId, style, css, data, basePath) Task<OverlayView> Create from inline XML attached to DOM element
CreateProfilePictureOverlayViewAsync(domId, imgStyle, frameStyle) Task<OverlayView> Create player profile picture overlay
CreateProfileNameOverlayViewAsync(domId, txtStyle, frameStyle, css) Task<OverlayView> Create player name overlay

Bulk Operations

Method Returns Description
ShowAsyncAll() Task Show all tracked overlays
UpdateAsyncAll(string data) Task Update all tracked overlays
DismissAsyncAll() Task Dismiss all tracked overlays
DestroyAllAsync() Task Destroy all tracked overlays

Event Handling

Method Parameters Description
SetCustomEventHandler(Action<string, string>) (eventStr, overlayViewId) Register handler for custom overlay events

OverlayView

Represents a single overlay view instance.

Fields

Field Type Description
id string Unique overlay identifier

Methods

Method Returns Description
ShowAsync() Task Show the overlay
UpdateAsync(string data) Task Update with new data
DismissAsync() Task Hide the overlay
GetStatus() Task<string> Get current status
GetInitialData() Task<string> Get initial data
GetErrors() Task<string> Get any errors
SetStyle(string name, string value) Task Set a CSS style property on the iframe
SetAttribute(string name, string value) Task Set an HTML attribute on the iframe
DestroyOverlayView() Task Remove the overlay from the DOM

Data Models

All data model classes are in the Meta.InstantGames namespace.

Ad Types

AdInstance

Represents a loaded ad unit.

Field Type Description
data AdInstanceData Placement and instance IDs
type AdType Type of ad
Method Returns Description
getPlacementID() string Audience Network placement ID
LoadAsync() Task<string> Preload the ad
ShowAsync() Task<string> Present the ad

AdInstanceData

Field Type
adInstanceID string
placementID string

Player Types

ConnectedPlayer

Field Type
playerId string
Method Returns
GetID() string

SignedASID

Method Returns Description
GetASID() string App-scoped user ID
GetSignature() string Verification signature

SignedPlayerInfo

Method Returns Description
GetPlayerID() string Player ID
GetSignature() string Verification signature

Context Types

ContextPlayer

Method Returns
GetID() string

GameContext

Method Returns Description
getID() string Context ID
getType() ContextType Context type
getSize() int Number of players

Payment Types

Product

Field Type Description
title string Product title
productID string Product identifier
description string Product description
imageURI string Product image URL
price string Formatted price string
priceCurrencyCode string Currency code
priceAmount float Numeric price

Purchase

Field Type Description
productID string Product identifier
purchaseToken string Token for consuming
paymentID string Payment identifier
isConsumed bool Whether consumed
purchaseTime string Timestamp
purchasePlatform string Platform (FB/GOOGLE/APPLE/OC)
signedRequest string Signed request for verification

PurchaseConfig

Field Type Description
productID string Product to purchase
developerPayload string Custom payload

Tournament Types

TournamentInstance

Field Type Description
tournamentID string Tournament identifier
contextID string Associated context
endTime double End timestamp
tournamentType string Type string
title string Display title
payload string Custom data

CreateTournamentConfig

Field Type Default Description
title string - Display title
image string - Base64 image
sortOrder TournamentSortOrder HIGHER_IS_BETTER Score ordering
scoreFormat TournamentScoreFormat NUMERIC Score display format
endTime long - Unix timestamp
tournamentType TournamentType - Tournament type
goal int - Target score

Payload Types

ShareWithOverlayPayload

Field Type Description
intent ShareIntent Share intent type
image string Base64 image
imageOverlayPath string Overlay XML path
pathToCSS string CSS file path
initialData Json Overlay initial data
media MediaParams GIF/video content
text string Share text
data Json Custom data
surface string Target surface (FACEBOOK/MESSENGER/WHATSAPP)
switchContext bool Switch context after share

InviteWithOverlayPayload

Field Type Description
image string Base64 image
imageOverlayPath string Overlay XML path
text LocalizableContent Invite text
cta LocalizableContent Call-to-action text
dialogTitle LocalizableContent Dialog title
data Json Custom data
filters List<InviteFilter> Invite filters
sections List<InviteSection> Invite sections

CustomUpdateWithOverlayPayload

Field Type Default Description
template string - Update template name
image string - Base64 image
imageOverlayPath string - Overlay XML path
text LocalizableContent - Update text
cta LocalizableContent - Call-to-action
data Json - Custom data
strategy UpdateStrategy IMMEDIATE Update strategy
notification UpdateNotificationType NO_PUSH Push notification type

LocalizableContent

Field Type Description
defaultText string Default text
localizations List<Localization> Per-locale translations

MediaParams

Field Type Description
gif MediaContent GIF URL
video MediaContent Video URL

Error Types

APIError

Property Type Description
code ErrorCodeType Error code
message string Error message

InstantGamesParseException

Custom exception thrown when JSON parsing fails on API responses.


Enums

Enum Values Description
AdType INTERSTITIAL, REWARDED_VIDEO, REWARDED_INTERSTITIAL Ad format types
ShareIntent INVITE, REQUEST, CHALLENGE, SHARE, CUSTOM Share dialog intent
ShareDestination NEWSFEED, GROUP, COPY_LINK, MESSENGER Share target (deprecated)
InviteFilter NEW_CONTEXT_ONLY, NEW_PLAYERS_ONLY, EXISTING_CONTEXT_ONLY, EXISTING_PLAYERS_ONLY Invite filtering
InviteSectionType GROUPS, USERS Invite section types
TournamentSortOrder HIGHER_IS_BETTER, LOWER_IS_BETTER Score sort direction
TournamentScoreFormat NUMERIC, TIME Score display format
TournamentType COLLABORATIVE, DEEP, DEFAULT Tournament type
UpdateStrategy IMMEDIATE, LAST, IMMEDIATE_CLEAR Update delivery strategy
UpdateNotificationType NO_PUSH, PUSH Push notification preference

All enums include a ToValue() extension method that returns the string representation.

String Constant Classes

These classes provide string constants (used in place of enums in some cases):

Class Constants
Platform IOS, ANDROID, WEB, MOBILE_WEB
ContextType SOLO, THREAD, GROUP
ContextFilter NEW_CONTEXT_ONLY, INCLUDE_EXISTING_CHALLENGES, NEW_PLAYERS_ONLY
PurchasePlatform FB, GOOGLE, APPLE, OC, UNKNOWN
ErrorCode 26 error code constants (see source)
UpdateAction CUSTOM

Infrastructure

WebGLBridge

The core C#-to-JavaScript interop bridge. Manages async callbacks between Unity C# and the browser JS runtime.

Method Returns Description
CallAsyncJavaScript(string fn, string args) Task<string> Call any FBInstant JS function
AdFunction(string fn, string adId, string args) Task<string> Call a function on an ad instance
OverlayFunction(string fn, string ovId, string args) Task<string> Call a function on an overlay view
RegisterPersistentCallback(string id, Action<string>) void Register a named persistent callback
GetScreenshotAsync() Task<string> Capture canvas as base64 JPEG
GetCanvasRect() Task<string> Get canvas DOM bounding rect
ClearAllPendingCallbacks() void Cancel all pending callbacks
Property Type Description
PendingCallbackCount int Number of pending async callbacks

Constants: STATUS_CODE_SUCCESS = 200, STATUS_CODE_ERROR = 400, CALLBACK_TIMEOUT_SECONDS = 60


WebGLPersistentCallbacks

Manages callbacks that persist across multiple JS invocations (event handlers).

Method Returns Description
RegisterCallback(Action<int, string>) (int, IntPtr) Register and get (id, pointer)
UnregisterCallback(int id) bool Unregister by ID
HasCallback(int id) bool Check existence
ClearAllCallbacks() void Clear all

Json Builder

Fluent API for constructing JSON payloads.

string json = Json.Object()
    .Prop("name", "My Game")
    .Prop("score", 100)
    .Prop("active", true)
    .Obj("player", p => p
        .Prop("id", "123")
        .Prop("level", 5))
    .Array("tags", "fun", "casual")
    .ToString();
Method Returns Description
Json.Object(bool prettyPrint) Json Create a new builder
Prop(string key, string value) Json Add string property
Prop(string key, int value) Json Add int property
Prop(string key, float value) Json Add float property
Prop(string key, bool value) Json Add bool property
Obj(string key, Action<Json> builder) Json Add nested object
Obj(string key, Json obj) Json Add nested object directly
Array(string key, params string[]) Json Add string array
Array(string key, params int[]) Json Add int array
ArrayOfObjects(string key, Action<JsonArray>) Json Add array of objects

JsonParser

Recursive descent JSON parser. Use instead of JsonUtility when you need dictionary support or polymorphic types.

JsonValue root = JsonParser.Parse(jsonString);
string name = root["name"].AsString();
int score = root["stats"]["score"].AsInt();
string deepValue = root.GetPath("outer.inner[0].name").AsString();
Method Returns Description
JsonParser.Parse(string json) JsonValue Parse JSON string into a value tree

JsonValue

Represents a parsed JSON node.

Property Type Description
Type JsonValueType Node type (Null/String/Number/Bool/Object/Array)
IsNull bool Whether the value is null
Count int Element count for arrays/objects
Keys IEnumerable<string> Object property keys
ArrayElements IEnumerable<JsonValue> Array elements
Method Returns Description
this[string key] JsonValue Object property access
this[int index] JsonValue Array index access
AsString() string Cast to string
AsInt() int Cast to int
AsLong() long Cast to long
AsFloat() float Cast to float
AsBool() bool Cast to bool
HasKey(string key) bool Check if key exists
GetPath(string path) JsonValue Dot-path access (supports array[0] syntax)

Editor Tools

Bundle Uploader

Menu: Window > Instant Games > Bundle Uploader

A full build-and-deploy workflow for Instant Games:

Project Optimiser

Menu: Window > Instant Games > Project Optimiser

Applies recommended WebGL build settings in one click.

Overlay View Builder

Menu: Window > Instant Games > Overlay View Builder

A visual drag-and-drop editor for creating Overlay View XML files:


Utility Components

DebugLogRedirect

MonoBehaviour that captures Unity debug logs and displays them on-screen via a UI Text component. Thread-safe with a 100-log limit.

FPSCounter

MonoBehaviour that displays current and average FPS using a rolling 64-sample window, updating every 0.25 seconds.

OverlayFollower

MonoBehaviour that creates an overlay view and continuously syncs its CSS position to follow a moving Unity UI element.

PluginExample

MonoBehaviour that generates a runtime testing UI with buttons for every FBInstant API function. Useful for manual API testing during development.