Docs
TikTok SDK for Unity
API | Function |
Initialization | |
| Initialize SDK |
| Determine the real machine environment |
Version information | |
| SDK version number |
| Game version number |
| Release version number |
| Container version number |
| Startup parameters |
| System information |
Account | |
| Log in |
| Authorized |
Pay | |
| Check balance |
| Recharge |
| Pay |
| Jump to balance page |
Entrance task | |
| Start the task |
| Get rewards |
Life cycle | |
| Lifecycle Manager |
| Exit listening |
File system | |
| File manager |
| Clear cache |
Data storage | |
| Attribute - Value Pair Storage |
| Save data |
| Load data |
| Delete data |
| Clear data |
| Data size |
Network | |
| Network type |
| Network status monitoring |
| Cancel monitoring |
| Weak connection listening |
| Cancel weak connection listening |
Shortcuts | |
| Create a shortcut |
| Shortcut rewards |
Social sharing | |
| Share messages |
Advertisement | |
| Incentive video ads |
Quickstart
Import the namespace and initialize the SDK before use:
using TTSDK;void Start()
{
TT.InitSDK((code, env) =>
{
if (code == 0)
{
Debug.Log("SDK Initialization successful");
// You can call other APIs after this
}
});
}Initialize
InitSDK
To initialize the TTSDK, initialization must be completed before all API calls .
TT.InitSDK((code, env) =>
{
// code: Error code; 0 indicates success
// env: Container environment information
Debug.Log($"Initialization complete. GameAppId: {env.GameAppId}");
});Error code description :
Code | Description |
0 | No errors |
1 | TT Unity SDK version not supported |
2 | Unity Engine version is not supported |
InContainerEnv
Determine whether it is running in the TT Container real machine environment.
if (TT.InContainerEnv)
{
Debug.Log("Running in a real device environment");
}
else
{
Debug.Log("Running in the editor or a non-container environment");
}s_ContainerEnv
Obtain container environment information.
ContainerEnv env = TT.s_ContainerEnv;Version information
TTSDKVersion
Get the TTSDK version number.
string sdkVersion = TT.TTSDKVersion;
// For example: "6.5.5"GameVersion
Get the game version number (instead of Application.version ).
string gameVersion = TT.GameVersion;GetLaunchOptionsSync
Get the parameters when Mini Programs start.
LaunchOption options = TT.GetLaunchOptionsSync();
Debug.Log($"Scene: {options.Scene}, Path: {options.Path}");Note : The parameter may be empty, and it needs to be checked when used; it needs to be called after the InitSDK callback.
GetSystemInfo
Obtain system information.
TTSystemInfo systemInfo = TT.GetSystemInfo();
Debug.Log(systemInfo.Serialize());Account login
Login
Login to obtain temporary login credentials.
TT.Login(
successCallback: (code) =>
{
// code: A temporary login credential used by the server to exchange for an openid
Debug.Log($"Login successful,code: {code}");
},
failedCallback: (errMsg) =>
{
Debug.Log($"Login failed: {errMsg}");
}
);Description:
Codecan be exchanged foropenid(unique user identifier)AnonymousCodecan be exchanged foranonymous_openid(same device same)
Authorize
Send an authorization request to the user in advance .
TT.Authorize(
scope: "user.info.basic",
success: (token) =>
{
Debug.Log($"authorization successful, token: {token}");
},
fail: (errCode, errMsg) =>
{
Debug.Log($"authorization failed: {errCode}, {errMsg}");
}
);Common scope:
user.info.basic: Basic user information
Payment system
Pay
Initiate payment .
TT.Pay(new TTPayParam
{
trade_order_id = "order_" + DateTime.Now.Ticks,
success = (data) =>
{
Debug.Log("Payment successful");
},
fail = (error) =>
{
Debug.Log($"Payment failed: {error}");
}
});NavigateToBalance
Jump to the balance page.
TT.NavigateToBalance(new TTNavigateToBalanceParam
{
success = (data) =>
{
Debug.Log("Redirect successful");
},
fail = (error) =>
{
Debug.Log($"Redirect failed: {error}");
}
});Entrance tasks
StartEntranceMission
Start the entrance task.
TT.StartEntranceMission(new TTStartEntranceMissionParam
{
success = (data) =>
{
Debug.Log("Entry task started");
},
fail = (error) =>
{
Debug.Log($"Startup failed: {error}");
}
});GetEntranceMissionReward
Obtain entrance task rewards.
TT.GetEntranceMissionReward(new TTGetEntranceMissionRewardParam
{
success = (data) =>
{
Debug.Log("Reward claimed successfullly");
},
fail = (error) =>
{
Debug.Log($"Retrieval failed: {error}");
}
});Game Lifecycle
GetAppLifeCycle
Obtain the application lifecycle manager.
TTAppLifeCycle lifeCycle = TT.GetAppLifeCycle();
// Listen for the Show event
lifeCycle.OnShow += (options) =>
{
Debug.Log("Game entered the foreground");
};
// Listen for the Hide event
lifeCycle.OnHide += () =>
{
Debug.Log("Game entered the background");
};File system
GetFileSystemManager
Obtain the file system manager.
TTFileSystemManager fsManager = TT.GetFileSystemManager();CleanAllFileCache
Clear all file caches.
TT.CleanAllFileCache((success) =>
{
Debug.Log($"success: {(success ? "success" : "failure")}");
});Data storage
PlayerPrefs
Note:
- Using PlayerPrefs = TT. PlayerPrefs; Using Unity's own PlayerPrefs will cause persistence failure.
- Lightweight Attribute - Value Pair storage (similar to Unity's PlayerPrefs). Has not been implemented.
// Store data
TT.PlayerPrefs.SetInt("score", 100);
TT.PlayerPrefs.SetFloat("volume", 0.8f);
TT.PlayerPrefs.SetString("playerName", "Player1");
// Read data
int score = TT.PlayerPrefs.GetInt("score");
float volume = TT.PlayerPrefs.GetFloat("volume");
string name = TT.PlayerPrefs.GetString("playerName");Save
Save game data (supports complex objects, maximum 50MB).
// 1. Define a serializable save class
[Serializable]
public class SaveData
{
public int level = 1;
public float progress = 0f;
public string playerName = "";
public List<string> items = new List<string>();
public Dictionary<string, bool> achievements = new Dictionary<string, bool>();
}
// 2. Save data
SaveData data = new SaveData
{
level = 10,
progress = 0.75f,
playerName = "Hero"
};
bool saved = TT.Save(data, "my_save");
Debug.Log($"Save: {(saved ? "success" : "failure")}");LoadSaving
Load game data.
SaveData loaded = TT.LoadSaving<SaveData>("my_save");
if (loaded != null)
{
Debug.Log($"Loaded level: {loaded.level}");
}DeleteSaving
Delete the specified archive.
TT.DeleteSaving<SaveData>("my_save");ClearAllSavings
Delete all archived data.
TT.ClearAllSavings();GetSavingDiskSize
Gets the total size of the archived data.
long size = TT.GetSavingDiskSize();
Debug.Log($"Archive size: {size} bytes ({size / 1024f:F2} KB)");Network capabilities
GetNetWorkType
Gets the current network type.
TT.GetNetWorkType(new GetNetworkTypeParam
{
Success = (result) =>
{
// Possible values: wifi, 2g, 3g, 4g, 5g, none, unknown
Debug.Log($"Network type: {result.NetworkType}");
},
Fail = (error) =>
{
Debug.Log($"Failed to retrieve: {error}");
}
});Shortcuts
AddShortcut
Create a desktop shortcut.
TT.AddShortcut(
csCallback: (success) =>
{
Debug.Log($"Create shortcut: {(success ? "Success" : "Failed")}");
}
);GetShortcutMissionReward
Get shortcut task reward information.
TT.GetShortcutMissionReward(new GetShortcutMissionRewardParam
{
Success = (result) =>
{
if (result.CanReceiveReward)
{
Debug.Log("User can claim shortcut reward");
}
else
{
Debug.Log("User cannot claim reward");
}
},
Fail = (error) =>
{
Debug.Log($"Failed to retrieve: {error.ErrMsg}");
},
Complete = () =>
{
Debug.Log("Request completed");
}
});Social sharing
ShareAppMessage
Actively pull up forwarding and enter the contact list selection interface.
TT.ShareAppMessage(new ShareAppMessageParam
{
ImageUrl = "https://example.com/image.jpg", // URL of the shared image
Subtitle = "subtitle", // subtitle
TemplateType = 1, // template type:1 or 2
Title = "main title", // main title
Path = "a/b", // share path
Query = "a=1&b=2", // query parameters, format: key1=value1&key2=value2
Success = () =>
{
Debug.Log("share successful");
},
Fail = (error) =>
{
Debug.Log($"share failed: {error.ErrMsg}");
},
Complete = () =>
{
Debug.Log("share complete (regardless of succcess or failure)");
}
});Parameter descriptions:
Parameter | Type | Required | Description |
| string | No | Share image URL |
| string | No | Subheading |
| int | No | Template style, 1 or 2, default is 1 |
| string | No | Main heading |
| string | No | Share path |
| string | No | Query parameters, format is |
| Action | Yes | Share successful callbacks |
| Action | Yes | Share failure callback |
| Action | Yes | Share completion callback (called on success or failure) |
Example:
// Share game level
TT.ShareAppMessage(new ShareAppMessageParam
{
ImageUrl = "https://your-cdn.com/level_share.jpg",
Title = "I cleared level 10!",
Subtitle = "Come and take the challenge!",
TemplateType = 1,
Path = "game/level",
Query = "level=10&score=5000",
Success = () =>
{
Debug.Log("Share successful; friends can enter the game via the shared link");
},
Fail = (error) =>
{
Debug.LogError($"Share failed: {error.ErrMsg}");
},
Complete = () =>
{
// Perform any cleanup tasks here
}
});Advertising system
CreateRewardedVideoAd
Create incentivized video ads. Each ad instance can only be displayed once. If you need to re-display the ad in other scenarios, you need to recreate it before displaying it.
// Create an ad instance
var rewardedAd = TT.CreateRewardedVideoAd(new CreateRewardedVideoAdParam
{
AdUnitId = "your_ad_unit_id" // Obtain this from the developer portal
});
// Listen for the close event
rewardedAd.OnClose += (isEnded) =>
{
if (isEnded)
{
Debug.Log("User watched the ad to completion; grant reward");
// TODO: Reward granting logic
}
else
{
Debug.Log("User closed the ad prematurely; do not grant reward");
}
};
// Listen for error events
rewardedAd.OnError += (errorCode, errorMessage) =>
{
Debug.Log($"Add error: {errorCode}, {errorMessage}");
};
// Show the ad
rewardedAd.Show();Best practices:
public class AdManager : MonoBehaviour
{
private TTRewardedVideoAd _rewardedAd;
private Action<bool> _rewardCallback;
void Start()
{
// Preload ads
PreloadRewardedAd();
}
void PreloadRewardedAd()
{
_rewardedAd = TT.CreateRewardedVideoAd(new CreateRewardedVideoAdParam
{
AdUnitId = "your_ad_unit_id"
});
_rewardedAd.OnClose += (isEnded) =>
{
_rewardCallback?.Invoke(isEnded);
_rewardCallback = null;
// Re-preload
PreloadRewardedAd();
};
_rewardedAd.OnError += (code, msg) =>
{
Debug.LogError($"Ad error: {code}, {msg}");
_rewardCallback?.Invoke(false);
_rewardCallback = null;
};
}
public void ShowRewardedAd(Action<bool> callback)
{
_rewardCallback = callback;
_rewardedAd?.Show();
}
}CreateInterstitialAd
Create interstitial video ads.
// Create an ad instance
var interstitialAd = TT.CreateInterstitialAd(new CreateInterstitialAdParam
{
InterstitialAdId = "your_interstitial_ad_id" // Obtain this from the Developer Portal
});
// Listen for the close event
interstitialAd.OnClose += () =>
{
Debug.Log("Interstitial ad closed");
// Logic to execute after the ad is closed
};
// Listen for error events
interstitialAd.OnError += (errorCode, errorMessage) =>
{
Debug.Log($"Interstitial ad error: {errorCode}, {errorMessage}");
};
// Show the ad
interstitialAd.Show();Precautions:
- Interstitial ads are not allowed to be displayed within 15 seconds of the ad module launch (calling any ad-related API will launch the ad module)
- The interval between two interstitial ads should not be less than 30 seconds
- Interstitial ads supports multiple instances and can create multiple instances in different scenarios
- Interstitial ads instances can only be displayed once. They will be automatically destroyed if there is a loading error or successful display, and need to be created again next time.
- You can call
Destroy ()to manually destroy ad instances
Best Practices:
public class AdManager : MonoBehaviour
{
private TTInterstitialAd _interstitialAd;
private float _lastShowTime = 0f;
private const float MIN_INTERVAL = 30f; // Minimum interval: 30 seconds
public void ShowInterstitialAd()
{
// Check the time interval
if (Time.time - _lastShowTime < MIN_INTERVAL)
{
Debug.Log($"距离上次展示不足 {MIN_INTERVAL} 秒,请稍后再试");
return;
}
// Create a new interstitial ad instance
_interstitialAd = TT.CreateInterstitialAd(new CreateInterstitialAdParam
{
InterstitialAdId = "your_interstitial_ad_id"
});
_interstitialAd.OnClose += () =>
{
Debug.Log("Interstitial ad closed");
_lastShowTime = Time.time;
_interstitialAd = null;
};
_interstitialAd.OnError += (code, msg) =>
{
Debug.LogError($"Interstitial ad error: {code}, {msg}");
_interstitialAd = null;
};
// Show the ad
_interstitialAd.Show();
}
void OnDestroy()
{
// Clean up resources
_interstitialAd?.Destroy();
}
}Incident reporting
ReportEvent
Custom event reporting interface.
TT.ReportEvent(new ReportEventParam
{
eventName = "your-event-name",
@params = new JsonData
{
["key1"] = "value1",
["key2"] = "value2"
},
success = () =>
{
Debug.Log("Event reporting successful");
},
fail = () =>
{
Debug.Log("Event reporting failed");
},
complete = () =>
{
Debug.Log("Event reporting completed (whether successful or failed)");
}
});Parameter descriptions:
Parameter | Type | Required | Description |
| string | Yes | Event name |
| JsonData | No | Event parameters, key-value format |
| Action | No | Interface call successful callback function |
| Action | No | Callback function for interface call failure |
| Action | No | Callback function at the end of the interface call (called on success or failure) |
Example:
// Report Game Level Completion Event
TT.ReportEvent(new ReportEventParam
{
eventName = "level_complete",
@params = new JsonData
{
["level"] = 10,
["score"] = 5000,
["time"] = 120
},
success = () =>
{
Debug.Log("Level completion event reported successfully");
},
fail = () =>
{
Debug.LogError("Level completion event reporting failed");
},
complete = () =>
{
// Perform cleanup tasks here
}
});
// Report User Action Event
TT.ReportEvent(new ReportEventParam
{
eventName = "user_action",
@params = new JsonData
{
["action"] = "button_click",
["button_id"] = "shop_enter",
["timestamp"] = DateTime.Now.Ticks
},
success = () => Debug.Log("User action event reported successfully"),
fail = () => Debug.LogError("User action event reporting failed")
});Precautions:
eventNamecannot be empty@Paramscan benull, if it isnullit will be automatically converted to an empty object{}- All callback functions are optional and can be
null
ReportScene
Start scene reporting
var jsonData = new JsonData();
jsonData["sceneId"] = 9999;
TT.ReportScene(jsonData,
success: (data) =>
{
Debug.Log($"ReportScene success: {(data != null ? JsonMapper.ToJson(data) : "null")}");
AddLog("ReportScene success");
},
failed: (code, msg) =>
{
Debug.LogError($"ReportScene failed: code={code}, msg={msg}");
AddLog($"ReportScene failed: [{code}] {msg}");
},
complete: () =>
{
Debug.Log("ReportScene complete");
AddLog("ReportScene complete");
});Parameter descriptions:
Field | Type | Required | Description |
| JsonData | Yes | Game scene loading finished, interactive scene Id is 9999 For example "{" sceneId ": 9999}//Required parameters "SceneId" Scenario ID, int type |
success | Action<JsonData> | No | Interface call successful callback function |
fail | Action<int, string> | No | Callback function for interface call failure |
complete | Action | No | Callback function at the end of the interface call (executed on successful or failed calls) |
Vibration function
VibrateShort
Make the phone vibrate for a short period of time.
TT.VibrateShort(new VibrateShortParam
{
Success = (result) =>
{
Debug.Log("Short vibration successful");
},
Fail = (error) =>
{
Debug.Log($"Vibration failed: Code={error.ErrorCode}, Msg={error.ErrMsg}");
},
Complete = () =>
{
Debug.Log("Vibration completed");
}
});Vibration duration:
- Android: 30ms
- iOS: 15ms
Parameter descriptions:
Parameter | Type | Description |
|
| Vibration successful callback function (optional) |
|
| Callback function for vibration failure (optional) |
|
| Callback function of vibration completion (optional, called on success or failure) |
Usage scenarios:
- Button click feedback
- Operation confirmation prompt
- Minor error message
VibrateLong
Make the phone vibrate for a long time.
TT.VibrateLong(new VibrateLongParam
{
Success = (result) =>
{
Debug.Log("Long vibration successful");
},
Fail = (error) =>
{
Debug.Log($"Vibration failed: Code={error.ErrorCode}, Msg={error.ErrMsg}");
},
Complete = () =>
{
Debug.Log("Vibration complete");
}
});Vibration duration:
- All platforms: 400ms
Parameter descriptions:
Parameter | Type | Description |
|
| Vibration successful callback function (optional) |
|
| Callback function for vibration failure (optional) |
|
| Callback function of vibration completion (optional, called on success or failure) |
Usage scenarios:
- Important operation confirmation
- Serious error prompt
- Game event notifications (such as obtaining rewards, completing tasks, etc.)
Complete example:
using TTSDK;
using UnityEngine;
public class VibrationExample : MonoBehaviour
{
void OnButtonClick()
{
// Trigger a short vibration when a button is clicked
TT.VibrateShort(new VibrateShortParam
{
Success = (result) =>
{
Debug.Log("Button vibration feedback successful");
},
Fail = (error) =>
{
Debug.LogWarning($"Vibration failed: {error.ErrMsg}");
}
});
}
void OnImportantEvent()
{
// Trigger a long vibration for important events
TT.VibrateLong(new VibrateLongParam
{
Success = (result) =>
{
Debug.Log("Important event vibration notification successful");
},
Fail = (error) =>
{
Debug.LogWarning($"Vibration failed: {error.ErrMsg}");
}
});
}
}Precautions:
- It needs to be tested on a real machine or a device that supports vibration
- Vibration function is also supported on WebGL platform
- If the device does not support vibration or has insufficient permissions, an error message will be returned in the
Failcallback - It is recommended to use short vibrations for user action feedback and long vibrations for important event notifications
- Avoid frequent vibration calls to avoid affecting the user experience
For You Feed Direct Out Game Ability
onFeedStatusChange
Add monitoring for switching between internal and external streams in the direct play scene
private void OnFeedStatusChangeCallback(OnFeedStatusChangeResult result)
{
Debug.Log($"OnFeedStatusChangeCallback, Type -->{result.Type.ToString()}");
}
private void OnFeedStatusChange()
{
TT.OnFeedStatusChange(OnFeedStatusChangeCallback);
}Parameter descriptions:
callback:
Callback is a delegate that receives the following parameters:
Field | Type | Description |
Type | enum FeedStatusEnum | The type of event currently entering or exiting the game |
Type is an enumeration type, and its enumeration values and descriptions are as follows:
Enumerated Value | Description |
FeedEnter | Enter the game from the feed |
FeedExit | Return from game to feed |
offFeedStatusChange
Delete listening for switching between internal and external streams in the direct play scene.
public static void OffFeedStatusChange(OnFeedStatusChangeCallback callback = null)Parameter descriptions
callback:
Callback is a delegate that receives the following parameters (if not passed, all callbacks will be deleted):
Field | Type | Description |
Type | enum FeedStatusEnum | The type of event currently entering or exiting the game |
API availability check (CanIUse)
Overview
CanIUse is used to check if the API is available on the current platform and version. It is recommended to use CanIUse to check before calling potentially unsupported APIs to avoid runtime errors.
Basic usage
using TTSDK;
// Check if the API is available
if (CanIUse.GetSystemInfo)
{
// API is available; call safely
var systemInfo = TT.GetSystemInfo();
Debug.Log($"Platform: {systemInfo.platform}");
}
else
{
// API is not available; use a fallback solution
Debug.Log("GetSystemInfo is not available");
}Examples of practical use cases
Scenario 1: Conditional feature enabled
void InitializeFeatures()
{
// Enable the vibration button only if vibration functionality is supported.
if (CanIUse.VibrateShort && CanIUse.VibrateLong)
{
vibrationButton.gameObject.SetActive(true);
}
else
{
vibrationButton.gameObject.SetActive(false);
Debug.Log("Vibration functionality is unavailable; the vibration button has been hidden");
}
}Scenario 2: Downgrade processing
void ShareContent()
{
// Prioritize using the new sharing API
if (CanIUse.ShareMessageToFriend)
{
TT.ShareAppMessage(new ShareAppMessageParam
{
// ... Sharing parameters
});
}
else
{
// Fallback to other sharing methods or prompt the user
Debug.Log("Sharing feature is unavailable");
ShowToast("The current version does not support the sharing feature");
}
}Notes
- Post-initialization check:
CanIUsecheck should be performed afterTT.InitSDK()is completed
List of Common CanIUse Properties
CanIUse property | Description | Client version requirements |
| Obtain system information | None |
| Short vibration | >= 43.8.0 |
| Long vibration | >= 43.8.0 |
| File manager | None |