Unity SDK - 方法参考

文档

Unity SDK - 方法参考

本文档全面介绍了Singular SDK中适用于Unity应用程序的所有方法。Singular Unity SDK 封装了本地 iOS 和 Android SDK,为移动归因、深度链接、收入跟踪和分析提供了统一的 C# 接口。每种方法都附有说明、签名和实际使用示例。


广告收入

SingularSDK.AdRevenue 方法

跟踪来自中介平台的广告收入。通过该方法,您可以报告 Unity 应用程序中广告印象产生的收入,支持广告货币化的归因和投资回报率分析。

签名

public static void AdRevenue(string currency, double amount)

使用示例

C#
// Track ad revenue from an ad impression
SingularSDK.AdRevenue("USD", 0.05);

清除全局属性

SingularSDK.ClearGlobalProperties 方法

删除之前设置的所有全局属性。全局属性是键值对,会自动包含在 SDK 跟踪的每个事件中。

签名

public static void ClearGlobalProperties()

使用示例

C#
// Clear all global properties
SingularSDK.ClearGlobalProperties();

为用户到用户归因活动创建推荐人短链接。 该方法生成的短链接可供用户共享,以跟踪推荐人并将新安装归因于特定推荐人。

public static void createReferrerShortLink(string baseLink, string referrerName, 
    string referrerId, Dictionary<string, string> passthroughParams, 
    ShortLinkCallback completionHandler)
C#
// 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);
        }
    }
);

自定义收入

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)

使用示例

C#
// 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()

使用示例

C#
// End the current session
SingularSDK.EndSingularSession();

事件

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)

使用示例

C#
// 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);

获取用户名

SingularSDK.GetAPID 方法

返回当前设备的 Singular APID(归因平台 ID)。 该标识符由 Singular 内部使用,用于归因和分析。

签名

public static string GetAPID()

使用示例

C#
// Get the APID
string apid = SingularSDK.GetAPID();
Debug.Log("APID: " + apid);

获取全局属性

SingularSDK.GetGlobalProperties 方法

以 JSON 字符串形式读取当前设置的所有全局属性。全局属性是键值对,会自动包含在每个跟踪事件中。

签名

public static string GetGlobalProperties()

使用示例

C#
// Get all global properties
string globalProps = SingularSDK.GetGlobalProperties();
Debug.Log("Global Properties: " + globalProps);

获取 IDFA

SingularSDK.GetIDFA 方法

返回当前 iOS 设备的 IDFA(广告商标识符)。 此方法需要适当的 ATT(应用程序跟踪透明度)授权。

签名

public static string GetIDFA()

使用示例

C#
// Get the IDFA (iOS only)
string idfa = SingularSDK.GetIDFA();
Debug.Log("IDFA: " + idfa);

获取限制数据共享

SingularSDK.GetLimitDataSharing 方法

返回当前数据共享限制状态。这表明 SDK 当前是否根据隐私设置限制数据收集和共享。

签名

public static bool GetLimitDataSharing()

使用示例

C#
// Check if data sharing is limited
bool isLimited = SingularSDK.GetLimitDataSharing();
Debug.Log("Data sharing limited: " + isLimited);

处理推送通知

SingularSDK.HandlePushNotification 方法

处理推送通知的有效载荷,以便进行归属和深层链接处理。 该方法应在应用程序收到推送通知时调用。

签名

public static void HandlePushNotification(Dictionary<string, string> pushNotificationPayload)

使用示例

C#
// Handle push notification (iOS only)
var pushPayload = new Dictionary<string, string>
{
    { "aps", "{"alert":"New message"}" },
    { "deep_link", "myapp://promo/spring2024" }
};

SingularSDK.HandlePushNotification(pushPayload);

应用内购买

SingularSDK.InAppPurchase 方法

跟踪来自 Unity IAP 的应用内购买。该方法支持 Unity IAP 4.x 和 5.x,并自动与 Apple 和 Google 验证购买收据。

签名

public static void InAppPurchase(Product product, Dictionary<string, object> attributes)

使用示例

C#
// Track in-app purchase
void OnPurchaseComplete(Product product)
{
    var attributes = new Dictionary<string, object>
    {
        { "category", "consumables" },
        { "location", "main_store" }
    };

    SingularSDK.InAppPurchase(product, attributes);
}

InitializeSingularSDK

SingularSDK.InitializeSingularSDK 方法

手动初始化 Singular SDK。只有在 SDK 配置中将 InitializeOnAwake 设为 false 时,才能调用此方法。否则,SDK 将自动初始化。

签名

public static void InitializeSingularSDK()

使用示例

C#
// Manually initialize the SDK (only if InitializeOnAwake = false)
SingularSDK.InitializeSingularSDK();

IsAllTrackingStopped

SingularSDK.IsAllTrackingStopped 方法

返回是否已停止所有跟踪。跟踪停止后,SDK 将不会发送任何事件或收集任何数据。

签名

public static bool IsAllTrackingStopped()

使用示例

C#
// Check if tracking is stopped
bool isTrackingStopped = SingularSDK.IsAllTrackingStopped();
Debug.Log("Tracking stopped: " + isTrackingStopped);

限制数据共享

SingularSDK.LimitDataSharing 方法

设置 SDK 是否应限制数据共享。启用后,SDK 将限制某些数据收集和共享活动,以遵守隐私法规。

签名

public static void LimitDataSharing(bool limitDataSharingValue)

使用示例

C#
// Enable limited data sharing based on user consent
SingularSDK.LimitDataSharing(true);

为卸载注册设备令牌

SingularSDK.RegisterDeviceTokenForUninstall 方法

为卸载跟踪注册设备令牌。这样,Singular 就能在用户卸载应用程序时进行检测。

签名

public static void RegisterDeviceTokenForUninstall(string APNSToken)

使用示例

C#
// Register APNS token for uninstall tracking (iOS only)
void OnTokenReceived(string token)
{
    SingularSDK.RegisterDeviceTokenForUninstall(token);
}

重启会话

SingularSDK.RestartSingularSession 方法

手动重启 Singular 会话。如果需要对会话管理进行明确控制,通常会在应用程序返回前台时调用该方法。

签名

public static void RestartSingularSession(string key, string secret)

使用示例

C#
// Restart the session
SingularSDK.RestartSingularSession("SDK KEY", "YOUR_SECRET");

ResumeAllTracking

SingularSDK.ResumeAllTracking 方法

恢复之前停止的所有跟踪。这将重新启用事件跟踪和数据收集。

签名

public static void ResumeAllTracking()

使用示例

C#
// Resume tracking
SingularSDK.ResumeAllTracking();

收入

SingularSDK.Revenue 方法

跟踪收入事件。这是跟踪购买和其他未通过 Unity IAP 自动跟踪的货币化事件的主要方法。

签名

public static void Revenue(string currency, double amount)

public static void Revenue(Dictionary<string, object> args, 
    string currency, double amount)

使用示例

C#
// 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);

设置年龄

SingularSDK.SetAge 方法

设置用户年龄,以便进行人口统计跟踪。年龄必须介于 0 和 100 之间。

签名

public static void SetAge(int age)

使用示例

C#
// Set user age (iOS only)
SingularSDK.SetAge(28);

SetConversionValueUpdatedHandler 方法

SingularSDK.SetConversionValueUpdatedHandler 方法

设置 SKAdNetwork 转换值更新(iOS 14+)的回调处理程序。每当转换值更新时,都会调用此处理程序。

签名

public static void SetConversionValueUpdatedHandler(SingularConversionValueUpdatedHandler handler)

使用示例

C#
// 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)

使用示例

C#
// Set conversion values updated handler (iOS only)
SingularSDK.SetConversionValuesUpdatedHandler((conversionValue, coarse, lockWindow) =>
{
    Debug.Log($"CV: {conversionValue}, Coarse: {coarse}, Lock: {lockWindow}");
});

设置客户用户标识

SingularSDK.SetCustomUserId 方法

设置与所有跟踪事件相关联的自定义用户 ID。这样就可以将 Singular 数据与自己的用户识别系统绑定。

签名

public static void SetCustomUserId(string customUserId)

使用示例

C#
// Set custom user ID
SingularSDK.SetCustomUserId("user_123456");

设置设备自定义用户 ID

SingularSDK.SetDeviceCustomUserId 方法

设置设备级自定义用户 ID。它不同于常规的自定义用户 ID,会在设备级别的应用程序会话中持续存在。

签名

public static void SetDeviceCustomUserId(string customUserId)

使用示例

C#
// Set device-level custom user ID
SingularSDK.SetDeviceCustomUserId("device_user_789");

SetFCMDeviceToken

SingularSDK.SetFCMDeviceToken 方法

设置用于跟踪推送通知和卸载检测的 FCM(Firebase Cloud Messaging)设备令牌。 仅适用于安卓系统。

签名

public static void SetFCMDeviceToken(string fcmDeviceToken)

使用示例

C#
// Set FCM token (Android only)
void OnFCMTokenReceived(string token)
{
    SingularSDK.SetFCMDeviceToken(token);
}

设置性别

SingularSDK.SetGender 方法

设置用户性别,以便进行人口统计跟踪。接受表示男性的 "m "或表示女性的 "f"。

签名

public static void SetGender(string gender)

使用示例

C#
// Set user gender (iOS only)
SingularSDK.SetGender("f");

设置全局属性

SingularSDK.SetGlobalProperty 方法

设置将随所有事件一起发送的全局属性。全局属性是键值对,会在多个事件中持续存在,直到被清除或更改。

签名

public static bool SetGlobalProperty(string key, string value, bool overrideExisting)

使用示例

C#
// 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);

设置IMEI

SingularSDK.SetIMEI 方法

设置用于跟踪的设备 IMEI。这在允许和偏好 IMEI 跟踪的地区非常有用。 仅适用于安卓系统。

签名

public static void SetIMEI(string imei)

使用示例

C#
// Set device IMEI (Android only)
SingularSDK.SetIMEI("123456789012345");

SetLimitAdvertisingIdentifiers

SingularSDK.SetLimitAdvertisingIdentifiers 方法

启用限制广告标识符模式。这会影响 SDK 收集和使用设备标识符进行跟踪的方式,适用于混合受众应用程序。

签名

public static void SetLimitAdvertisingIdentifiers(bool isEnabled)

使用示例

C#
// Enable limited advertising identifiers mode
SingularSDK.SetLimitAdvertisingIdentifiers(true);

SetSingularDeviceAttributionCallbackHandler

SingularSDK.SetSingularDeviceAttributionCallbackHandler 方法

设置接收设备属性数据的回调处理程序。当归因数据可用时,该处理程序将被调用,以便您访问活动和来源信息。

  1. 使用以下处理程序代码创建 C# 脚本AttributionCallback

  2. 在层次结构中创建一个 Emtpy 对象,并将其置于 SingularSDKObject 的下方。

  3. 在空对象中添加脚本组件,关联AttributionCallback 处理程序脚本

签名

public static void SetSingularDeviceAttributionCallbackHandler(
    SingularDeviceAttributionCallbackHandler handler)

使用示例

C#
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方法

设置奇异链接(深层链接)的回调处理程序。该处理程序会在解析深层链接时调用,并提供链接参数和直通数据。

  1. 使用下面的处理程序代码创建 C# 脚本DeepLinkManager

  2. 在层次结构中创建一个 Emtpy 对象,并将其置于 SingularSDKObject 的下方。

  3. 在空对象中添加一个脚本组件,关联DeepLinkManager 处理程序脚本

签名

public static void SetSingularLinkHandler(SingularLinkHandler linkHandler)

使用示例

C#
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方法

设置接收奇异设备 ID(SDID)的回调处理程序。当 SDID 在 SDK 初始化后可用时,将调用该处理程序。

  1. 使用下面的处理程序代码创建 C# 脚本SDIDManager

  2. 在层次结构中创建一个 Emtpy 对象,并将其置于 SingularSDKObject 的下方。

  3. 在空对象中添加脚本组件,关联SDIDManager 处理程序脚本

签名

public static void SetSingularSdidAccessorHandler(SingularSdidAccessorHandler handler)

使用示例

C#
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
    }   
}

SkanRegisterAppForAdNetworkAttribution

SingularSDK.SkanRegisterAppForAdNetworkAttribution 方法

为 SKAdNetwork 归属注册应用程序。该方法应在 iOS 14.5+ SKAdNetwork 支持的应用程序生命周期早期调用。

签名

public static void SkanRegisterAppForAdNetworkAttribution()

使用示例

C#
// Register for SKAdNetwork attribution (iOS only)
SingularSDK.SkanRegisterAppForAdNetworkAttribution();

SkanUpdateConversionValue

SingularSDK.SkanUpdateConversionValue 方法

手动更新 SKAdNetwork 转换值。此方法在启用手动转换值管理时使用。

签名

public static bool SkanUpdateConversionValue(int conversionValue)

public static bool SkanUpdateConversionValue(int conversionValue, int coarse, bool lockWindow)

使用示例

C#
// Update conversion value (iOS only)
bool success = SingularSDK.SkanUpdateConversionValue(5);

// Update with coarse value and lock (SKAdNetwork 4.0+)
bool success2 = SingularSDK.SkanUpdateConversionValue(10, 2, false);

停止所有跟踪

SingularSDK.StopAllTracking 方法

停止所有跟踪和数据收集。停止跟踪后,SDK 将不会发送任何事件或收集任何数据,直到恢复跟踪。

签名

public static void StopAllTracking()

使用示例

C#
// Stop all tracking
SingularSDK.StopAllTracking();

TrackingOptIn

SingularSDK.TrackingOptIn 方法

表示用户已选择接受跟踪。当用户明确同意数据收集和跟踪时,应调用此方法。

签名

public static void TrackingOptIn()

使用示例

C#
// User opted in to tracking
SingularSDK.TrackingOptIn();

TrackingUnder13

SingularSDK.TrackingUnder13 方法

表示用户未满 13 周岁,这将影响数据收集以符合 COPPA(《儿童在线隐私保护法案》)规定。

签名

public static void TrackingUnder13()

使用示例

C#
// User is under 13 years old
SingularSDK.TrackingUnder13();

取消设置客户用户标识

SingularSDK.UnsetCustomUserId 方法

删除之前设置的自定义用户 ID。调用此方法后,事件将不再与自定义用户 ID 关联,直到设置了新的用户 ID。

签名

public static void UnsetCustomUserId()

使用示例

C#
// Remove custom user ID (e.g., on logout)
SingularSDK.UnsetCustomUserId();

UnsetGlobalProperty

SingularSDK.UnsetGlobalProperty 方法

通过键删除特定全局属性。这将阻止该属性与后续事件一起发送。

签名

public static void UnsetGlobalProperty(string key)

使用示例

C#
// Remove a specific global property
SingularSDK.UnsetGlobalProperty("user_level");