Unity SDK - 方法参考
本文档全面介绍了Singular SDK中适用于Unity应用程序的所有方法。Singular Unity SDK 封装了本地 iOS 和 Android SDK,为移动归因、深度链接、收入跟踪和分析提供了统一的 C# 接口。每种方法都附有说明、签名和实际使用示例。
完整的配置选项列表请参阅Unity SDK 配置参考。
AdRevenue
SingularSDK.AdRevenue 方法
跟踪来自中介平台的广告收入。通过该方法,您可以报告 Unity 应用程序中广告展示产生的收入,支持广告变现的归因和投资回报率分析。
签名
public static void AdRevenue(SingularAdData adData)
使用示例
// Build the ad data, then report it
SingularAdData adData = new SingularAdData("AdMob", "USD", 0.05);
SingularSDK.AdRevenue(adData);
ClearGlobalProperties
SingularSDK.ClearGlobalProperties 方法
删除之前设置的所有全局属性。全局属性是键值对,会自动包含在 SDK 跟踪的每个事件中。
签名
public static void ClearGlobalProperties()
使用示例
// Clear all global properties
SingularSDK.ClearGlobalProperties();
createReferrerShortLink
SingularSDK.createReferrerShortLink 方法
为用户到用户归因活动创建推荐人短链接。 该方法生成的短链接可供用户共享,以跟踪推荐人并将新安装归因于特定推荐人。
签名
public static void createReferrerShortLink(string baseLink, string referrerName,
string referrerId, Dictionary<string, string> passthroughParams,
ShortLinkCallback completionHandler)
使用示例
// Create a referrer short link
var passthroughParams = new Dictionary<string, string>
{
{ "promo_code", "WELCOME10" },
{ "campaign", "spring_2024" }
};
SingularSDK.createReferrerShortLink(
"https://yourapp.sng.link/12345",
"John Doe",
"user_12345",
passthroughParams,
(data, error) =>
{
if (error == null)
{
Debug.Log("Short link created: " + data);
}
else
{
Debug.LogError("Error creating short link: " + error);
}
}
);
CustomRevenue
SingularSDK.CustomRevenue 方法
使用指定的事件名称跟踪自定义收入事件。这样就可以跟踪应用内购买以外的收入来源,如订阅或其他变现方式。
签名
public static void CustomRevenue(string eventName, string currency, double amount)
public static void CustomRevenue(Dictionary<string, object> args,
string eventName, string currency, double amount)
使用示例
// Track custom revenue event
SingularSDK.CustomRevenue("subscription_renewal", "USD", 9.99);
// Track custom revenue with additional attributes
var attributes = new Dictionary<string, object>
{
{ "subscription_type", "premium" },
{ "billing_period", "monthly" }
};
SingularSDK.CustomRevenue(attributes, "subscription_renewal", "USD", 9.99);
EndSingularSession
SingularSDK.EndSingularSession 方法
手动结束当前的 Singular 会话。如果需要对会话管理进行明确控制,通常会在应用程序进入后台时调用该方法。
签名
public static void EndSingularSession()
使用示例
// End the current session
SingularSDK.EndSingularSession();
Event
SingularSDK.Event 方法
跟踪 Unity 应用程序中的自定义事件。跟踪事件时可以只使用名称,也可以使用附加属性作为键值对,以便进行更详细的分析。
签名
public static void Event(string name)
public static void Event(Dictionary<string, object> args, string name)
public static void Event(string name, params object[] args)
使用示例
// Track a simple event
SingularSDK.Event("level_completed");
// Track event with dictionary attributes
var attributes = new Dictionary<string, object>
{
{ "level", 5 },
{ "score", 1250 },
{ "time_seconds", 45.3 }
};
SingularSDK.Event(attributes, "level_completed");
// Track event with params array (key-value pairs)
SingularSDK.Event("item_purchased",
"item_name", "Golden Sword",
"item_category", "weapons",
"price", 4.99);
GetAPID
SingularSDK.GetAPID 方法
返回当前设备的 Singular APID(归因平台 ID)。 该标识符由 Singular 内部使用,用于归因和分析。
签名
public static string GetAPID()
使用示例
// Get the APID
string apid = SingularSDK.GetAPID();
Debug.Log("APID: " + apid);
GetGlobalProperties
SingularSDK.GetGlobalProperties 方法
以 JSON 字符串形式读取当前设置的所有全局属性。全局属性是键值对,会自动包含在每个跟踪事件中。
签名
public static string GetGlobalProperties()
使用示例
// Get all global properties
string globalProps = SingularSDK.GetGlobalProperties();
Debug.Log("Global Properties: " + globalProps);
GetIDFA
SingularSDK.GetIDFA 方法
返回当前 iOS 设备的 IDFA(广告商标识符)。 此方法需要适当的 ATT(应用程序跟踪透明度)授权。
签名
public static string GetIDFA()
使用示例
// Get the IDFA (iOS only)
string idfa = SingularSDK.GetIDFA();
Debug.Log("IDFA: " + idfa);
GetLimitDataSharing
SingularSDK.GetLimitDataSharing 方法
返回当前数据共享限制状态。这表明 SDK 当前是否根据隐私设置限制数据收集和共享。
签名
public static bool GetLimitDataSharing()
使用示例
// Check if data sharing is limited
bool isLimited = SingularSDK.GetLimitDataSharing();
Debug.Log("Data sharing limited: " + isLimited);
HandlePushNotification
SingularSDK.HandlePushNotification 方法
处理推送通知的有效载荷,以便进行归因和深层链接处理。 该方法应在应用程序收到推送通知时调用。
签名
public static void HandlePushNotification(Dictionary<string, string> pushNotificationPayload)
使用示例
// Handle push notification (iOS only)
var pushPayload = new Dictionary<string, string>
{
{ "aps", "{"alert":"New message"}" },
{ "deep_link", "myapp://promo/spring2024" }
};
SingularSDK.HandlePushNotification(pushPayload);
InAppPurchase
SingularSDK.InAppPurchase 方法
跟踪来自 Unity IAP 的应用内购买,并与 Apple 和 Google 验证购买收据。
可用的重载取决于您的 Unity IAP 版本。SingularSDK.asmdef 针对 com.unity.purchasing 包声明了 versionDefines,因此 Unity 会为 4.x 包自动定义 SINGULAR_SDK_IAP_ENABLED__IAP_4,为 5.x 自动定义 SINGULAR_SDK_IAP_ENABLED__IAP_5。Order 重载仅存在于 5.x,Product 重载仅存在于 4.x,因此在一个版本中可编译的签名在另一个版本中无法编译。如果未安装 Unity IAP 包,则这些重载均不存在。
签名
Unity IAP 5.x — 接收 UnityEngine.Purchasing.Order:
public static void InAppPurchase(Order order)
public static void InAppPurchase(Order order, Dictionary<string, object> attributes)
public static void InAppPurchase(Order order, bool isRestored)
public static void InAppPurchase(Order order, string eventName, Dictionary<string, object> attributes)
public static void InAppPurchase(Order order, string eventName, Dictionary<string, object> attributes, bool isRestored)
Unity IAP 4.x — 接收 UnityEngine.Purchasing.Product:
public static void InAppPurchase(Product product, Dictionary<string, object> attributes, bool isRestored = false)
public static void InAppPurchase(IEnumerable<Product> products, Dictionary<string, object> attributes, bool isRestored = false)
public static void InAppPurchase(string eventName, IEnumerable<Product> products, Dictionary<string, object> attributes, bool isRestored = false)
两个版本均可用 —— 两者中唯一同时存在的重载,但参数列表不同:
// Unity IAP 4.x
public static void InAppPurchase(string eventName, Product product, Dictionary<string, object> attributes, bool isRestored = false)
// Unity IAP 5.x — an additional Order parameter
public static void InAppPurchase(string eventName, Product product, Order order, Dictionary<string, object> attributes, bool isRestored = false)
使用示例
// Unity IAP 4.x — Product-based
void OnPurchaseComplete(Product product)
{
var attributes = new Dictionary<string, object>
{
{ "category", "consumables" },
{ "location", "main_store" }
};
SingularSDK.InAppPurchase(product, attributes);
}// Unity IAP 5.x — Order-based
void OnPurchaseConfirmed(Order order)
{
var attributes = new Dictionary<string, object>
{
{ "category", "consumables" },
{ "location", "main_store" }
};
SingularSDK.InAppPurchase(order, attributes);
}InitializeSingularSDK
SingularSDK.InitializeSingularSDK 方法
手动初始化 Singular SDK。只有在 SDK 配置中将 InitializeOnAwake 设为 false 时,才能调用此方法。否则,SDK 将自动初始化。
签名
public static void InitializeSingularSDK()
使用示例
// Manually initialize the SDK (only if InitializeOnAwake = false)
SingularSDK.InitializeSingularSDK();
IsAllTrackingStopped
SingularSDK.IsAllTrackingStopped 方法
返回是否已停止所有跟踪。跟踪停止后,SDK 将不会发送任何事件或收集任何数据。
签名
public static bool IsAllTrackingStopped()
使用示例
// Check if tracking is stopped
bool isTrackingStopped = SingularSDK.IsAllTrackingStopped();
Debug.Log("Tracking stopped: " + isTrackingStopped);
LimitDataSharing
SingularSDK.LimitDataSharing 方法
设置 SDK 是否应限制数据共享。启用后,SDK 将限制某些数据收集和共享活动,以遵守隐私法规。
签名
public static void LimitDataSharing(bool limitDataSharingValue)
使用示例
// Enable limited data sharing based on user consent
SingularSDK.LimitDataSharing(true);
RegisterDeviceTokenForUninstall
SingularSDK.RegisterDeviceTokenForUninstall 方法
为卸载跟踪注册设备令牌。这样,Singular 就能在用户卸载应用程序时进行检测。
签名
public static void RegisterDeviceTokenForUninstall(string APNSToken)
使用示例
// Register APNS token for uninstall tracking (iOS only)
void OnTokenReceived(string token)
{
SingularSDK.RegisterDeviceTokenForUninstall(token);
}
RegisterTokenForUninstall
SingularSDK.RegisterTokenForUninstall 方法
通过一次调用即可在两个平台上注册用于卸载归因的设备推送令牌。在 iOS 上转发到 RegisterDeviceTokenForUninstall(APNs 令牌);在 Android 上转发到 SetFCMDeviceToken(FCM 令牌)。请使用它,而不必自行按平台分支。
请传入您所在平台实际签发的令牌。此方法只负责路由该值,不会在格式之间转换。在 iOS 上,APNs 令牌必须是长度为偶数的十六进制字符串,RegisterDeviceTokenForUninstall 会对其进行校验,否则将拒绝。
签名
public static void RegisterTokenForUninstall(string token)
使用示例
// One call for both platforms — APNs on iOS, FCM on Android
void OnPushTokenReceived(string token)
{
SingularSDK.RegisterTokenForUninstall(token);
}RestartSingularSession
SingularSDK.RestartSingularSession 方法
手动重启 Singular 会话。如果需要对会话管理进行明确控制,通常会在应用程序返回前台时调用该方法。
签名
public static void RestartSingularSession(string key, string secret)
使用示例
// Restart the session
SingularSDK.RestartSingularSession("SDK KEY", "YOUR_SECRET");
ResumeAllTracking
SingularSDK.ResumeAllTracking 方法
恢复之前停止的所有跟踪。这将重新启用事件跟踪和数据收集。
签名
public static void ResumeAllTracking()
使用示例
// Resume tracking
SingularSDK.ResumeAllTracking();
Revenue
SingularSDK.Revenue 方法
跟踪收入事件。这是跟踪购买和其他未通过 Unity IAP 自动跟踪的变现事件的主要方法。
签名
public static void Revenue(string currency, double amount)
public static void Revenue(Dictionary<string, object> args,
string currency, double amount)
使用示例
// Track simple revenue
SingularSDK.Revenue("USD", 9.99);
// Track revenue with attributes
var attributes = new Dictionary<string, object>
{
{ "product_id", "premium_upgrade" },
{ "product_name", "Premium Subscription" },
{ "product_category", "subscriptions" }
};
SingularSDK.Revenue(attributes, "USD", 9.99);
SetAge
SingularSDK.SetAge 方法
设置用户年龄,以便进行人口统计跟踪。年龄必须介于 0 和 100 之间。
签名
public static void SetAge(int age)
使用示例
// Set user age (iOS only)
SingularSDK.SetAge(28);
SetConversionValueUpdatedHandler
SingularSDK.SetConversionValueUpdatedHandler 方法
设置 SKAdNetwork 转换值更新(iOS 14+)的回调处理程序。每当转换值更新时,都会调用此处理程序。
签名
public static void SetConversionValueUpdatedHandler(SingularConversionValueUpdatedHandler handler)
使用示例
// Set conversion value updated handler (iOS only)
SingularSDK.SetConversionValueUpdatedHandler((conversionValue) =>
{
Debug.Log("Conversion value updated: " + conversionValue);
});
SetConversionValuesUpdatedHandler
SingularSDK.SetConversionValuesUpdatedHandler 方法
设置 SKAdNetwork 4.0+ 转换值更新的回调处理程序。 该处理程序提供转换值、粗转换值和锁定状态。
签名
public static void SetConversionValuesUpdatedHandler(SingularConversionValuesUpdatedHandler handler)
使用示例
// Set conversion values updated handler (iOS only)
SingularSDK.SetConversionValuesUpdatedHandler((conversionValue, coarse, lockWindow) =>
{
Debug.Log($"CV: {conversionValue}, Coarse: {coarse}, Lock: {lockWindow}");
});
SetCustomUserId
SingularSDK.SetCustomUserId 方法
设置与所有跟踪事件相关联的自定义用户 ID。这样就可以将 Singular 数据与自己的用户识别系统绑定。
签名
public static void SetCustomUserId(string customUserId)
使用示例
// Set custom user ID
SingularSDK.SetCustomUserId("user_123456");
SetDeviceCustomUserId
SingularSDK.SetDeviceCustomUserId 方法
此方法已废弃,不再使用。
签名
public static void SetDeviceCustomUserId(string customUserId)
使用示例
// Set device-level custom user ID
SingularSDK.SetDeviceCustomUserId("device_user_789");
SetFCMDeviceToken
SingularSDK.SetFCMDeviceToken 方法
设置用于跟踪推送通知和卸载检测的 FCM(Firebase Cloud Messaging)设备令牌。 仅适用于安卓系统。
签名
public static void SetFCMDeviceToken(string fcmDeviceToken)
使用示例
// Set FCM token (Android only)
void OnFCMTokenReceived(string token)
{
SingularSDK.SetFCMDeviceToken(token);
}
SetGender
SingularSDK.SetGender 方法
设置用户性别,以便进行人口统计跟踪。接受表示男性的 "m "或表示女性的 "f"。
签名
public static void SetGender(string gender)
使用示例
// Set user gender (iOS only)
SingularSDK.SetGender("f");
SetGlobalProperty
SingularSDK.SetGlobalProperty 方法
设置将随所有事件一起发送的全局属性。全局属性是键值对,会在多个事件中持续存在,直到被清除或更改。
签名
public static bool SetGlobalProperty(string key, string value, bool overrideExisting)
使用示例
// Set a global property
bool success = SingularSDK.SetGlobalProperty("user_level", "premium", true);
// Set multiple global properties
SingularSDK.SetGlobalProperty("app_version", "2.1.0", true);
SingularSDK.SetGlobalProperty("platform", "unity", true);
SetIMEI
SingularSDK.SetIMEI 方法
设置用于跟踪的设备 IMEI。这在允许和偏好 IMEI 跟踪的地区非常有用。 仅适用于安卓系统。
签名
public static void SetIMEI(string imei)
使用示例
// Set device IMEI (Android only)
SingularSDK.SetIMEI("123456789012345");
SetLimitAdvertisingIdentifiers
SingularSDK.SetLimitAdvertisingIdentifiers 方法
启用限制广告标识符模式。这会影响 SDK 收集和使用设备标识符进行跟踪的方式,适用于混合受众应用程序。
签名
public static void SetLimitAdvertisingIdentifiers(bool isEnabled)
使用示例
// Enable limited advertising identifiers mode
SingularSDK.SetLimitAdvertisingIdentifiers(true);
SetSingularDeviceAttributionCallbackHandler
BETA 功能 - 设置在设备归因数据可用时调用的回调函数。
SingularSDK.SetSingularDeviceAttributionCallbackHandler 方法
设置接收设备属性数据的回调处理程序。当归因数据可用时,该处理程序将被调用,以便您访问活动和来源信息。
-
使用以下处理程序代码创建 C# 脚本
AttributionCallback -
在层次结构中创建一个 Emtpy 对象,并将其置于 SingularSDKObject 的下方。
-
在空对象中添加脚本组件,关联
AttributionCallback处理程序脚本
仅包含有值的字段,因此读取前请先检查该键是否存在。大多数安装只会返回部分字段,具体包含哪些字段取决于 Singular 匹配到的触点。
| 键 | 类型 | 说明 |
|---|---|---|
network |
string | 回调触发时始终包含。未匹配到触点时为 "Organic"。 |
campaign_id |
string | 触点提供时包含。 |
campaign_name |
string | 触点提供时包含。 |
subcampaign_id |
string | 触点提供时包含。并非所有来源都会提供。 |
subcampaign_name |
string | 触点提供时包含。并非所有来源都会提供。 |
creative_id |
string | 触点提供时包含。并非所有来源都会提供。 |
creative_name |
string | 触点提供时包含。并非所有来源都会提供。 |
passthrough |
string | 链接附带透传值时包含。 |
match_type |
string | 触点提供时包含。如需取值列表,请联系 Singular。 |
click_timestamp |
long | 触点提供时包含。为 epoch 微秒,除以 1,000,000 可换算为秒。 |
签名
public static void SetSingularDeviceAttributionCallbackHandler(
SingularDeviceAttributionCallbackHandler handler)
使用示例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Singular;
public class AttributionCallback : MonoBehaviour, SingularDeviceAttributionCallbackHandler
{
void Awake()
{
Debug.Log("Registering SingularDeviceAttributionCallbackHandler");
SingularSDK.SetSingularDeviceAttributionCallbackHandler(this);
}
public void OnSingularDeviceAttributionCallback(Dictionary attributionInfo) {
foreach(var kvp in attributionInfo)
{
Debug.Log($"OnSingularDeviceAttributionCallback Key: {kvp.Key}, Value: {kvp.Value}");
}
}
}
SetSingularLinkHandler
SingularSDK.SetSingularLinkHandler方法
设置Singular链接(深层链接)的回调处理程序。该处理程序会在解析深层链接时调用,并提供链接参数和直通数据。
-
使用下面的处理程序代码创建 C# 脚本
DeepLinkManager -
在层次结构中创建一个 Emtpy 对象,并将其置于 SingularSDKObject 的下方。
-
在空对象中添加一个脚本组件,关联
DeepLinkManager处理程序脚本
签名
public static void SetSingularLinkHandler(SingularLinkHandler linkHandler)
使用示例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Singular;
public class DeepLinkManager : MonoBehaviour, SingularLinkHandler
{
void Awake()
{
Debug.Log("Registering SingularLink Handler");
SingularSDK.SetSingularLinkHandler(this);
}
public void OnSingularLinkResolved(SingularLinkParams linkParams)
{
Debug.Log("SingularLink Resolved");
// Extract parameters from the tracking link
string deeplink = linkParams.Deeplink;
string passthrough = linkParams.Passthrough;
bool isDeferred = linkParams.IsDeferred;
// Log the parameters
Debug.Log($"SingularLink Deeplink: {deeplink ?? "null"}");
Debug.Log($"SingularLink Passthrough: {passthrough ?? "null"}");
Debug.Log($"SingularLink is Deferred: {isDeferred}");
// Handle deep link routing
if (!string.IsNullOrEmpty(deeplink))
{
HandleDeepLink(deeplink, isDeferred);
}
}
private void HandleDeepLink(string url, bool isDeferred)
{
// Your deep link routing logic here
Debug.Log($"SingularLink Routing to: {url} (Deferred: {isDeferred})");
// Example: Parse the URL and navigate to the appropriate screen
// if (url.Contains("product"))
// {
// NavigateToProduct(url);
// }
}
}
SetSingularSdidAccessorHandler
SingularSDK.SetSingularSdidAccessorHandler方法
设置接收Singular设备 ID(SDID)的回调处理程序。当 SDID 在 SDK 初始化后可用时,将调用该处理程序。
-
使用下面的处理程序代码创建 C# 脚本
SDIDManager -
在层次结构中创建一个 Emtpy 对象,并将其置于 SingularSDKObject 的下方。
-
在空对象中添加脚本组件,关联
SDIDManager处理程序脚本
签名
public static void SetSingularSdidAccessorHandler(SingularSdidAccessorHandler handler)
使用示例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Singular;
public class SDIDManager : MonoBehaviour, SingularSdidAccessorHandler
{
void Awake()
{
Debug.Log("Registering SingularSdidAccessorHandler");
SingularSDK.SetSingularSdidAccessorHandler(this);
}
public void DidSetSdid(string sdid)
{
Debug.Log($"SDID Set: {sdid}");
}
public void SdidReceived(string sdid)
{
Debug.Log($"SDID Set: {sdid}");
// Store or use the SDID as needed
}
}
SkanGetConversionValue
SingularSDK.SkanGetConversionValue 方法
返回 Singular 当前为该设备保存的 SKAdNetwork 转化值;如果尚未设置任何值,则返回 null。可用于确认 SkanUpdateConversionValue 调用是否生效。
仅限 iOS。在其他所有平台上此方法均返回 null。它是同步的:直接读取原生值,而不是通过回调传递。表示"未设置"的原生值 -1 会以 null 返回,而不是 -1。
签名
public static int? SkanGetConversionValue()
使用示例
// Read back the current conversion value
int? conversionValue = SingularSDK.SkanGetConversionValue();
if (conversionValue.HasValue)
{
Debug.Log($"Current SKAN conversion value: {conversionValue.Value}");
}
else
{
Debug.Log("No SKAN conversion value has been set yet");
}SkanRegisterAppForAdNetworkAttribution
SingularSDK.SkanRegisterAppForAdNetworkAttribution 方法
为 SKAdNetwork 归因注册应用程序。该方法应在 iOS 14.5+ SKAdNetwork 支持的应用程序生命周期早期调用。
签名
public static void SkanRegisterAppForAdNetworkAttribution()
使用示例
// Register for SKAdNetwork attribution (iOS only)
SingularSDK.SkanRegisterAppForAdNetworkAttribution();
SkanUpdateConversionValue
SingularSDK.SkanUpdateConversionValue 方法
手动更新 SKAdNetwork 转换值。此方法在启用手动转换值管理时使用。
签名
public static bool SkanUpdateConversionValue(int conversionValue)
public static void SkanUpdateConversionValue(int conversionValue, int coarse, bool lockWindow)
使用示例
// Update conversion value (iOS only)
bool success = SingularSDK.SkanUpdateConversionValue(5);
// Update with coarse value and lock (SKAdNetwork 4.0+)
SingularSDK.SkanUpdateConversionValue(10, 2, false);
StopAllTracking
SingularSDK.StopAllTracking 方法
停止所有跟踪和数据收集。停止跟踪后,SDK 将不会发送任何事件或收集任何数据,直到恢复跟踪。
签名
public static void StopAllTracking()
使用示例
// Stop all tracking
SingularSDK.StopAllTracking();
TrackingOptIn
SingularSDK.TrackingOptIn 方法
表示用户已选择接受跟踪。当用户明确同意数据收集和跟踪时,应调用此方法。
签名
public static void TrackingOptIn()
使用示例
// User opted in to tracking
SingularSDK.TrackingOptIn();
TrackingUnder13
SingularSDK.TrackingUnder13 方法
表示用户未满 13 周岁,这将影响数据收集以符合 COPPA(《儿童在线隐私保护法案》)规定。
签名
public static void TrackingUnder13()
使用示例
// User is under 13 years old
SingularSDK.TrackingUnder13();
UnsetCustomUserId
SingularSDK.UnsetCustomUserId 方法
删除之前设置的自定义用户 ID。调用此方法后,事件将不再与自定义用户 ID 关联,直到设置了新的用户 ID。
签名
public static void UnsetCustomUserId()
使用示例
// Remove custom user ID (e.g., on logout)
SingularSDK.UnsetCustomUserId();
UnsetGlobalProperty
SingularSDK.UnsetGlobalProperty 方法
通过键删除特定全局属性。这将阻止该属性与后续事件一起发送。
签名
public static void UnsetGlobalProperty(string key)
使用示例
// Remove a specific global property
SingularSDK.UnsetGlobalProperty("user_level");