---
title: "在 Unity SDK 中检查订阅状态"
description: "了解如何在 Unity 应用中使用 Adapty 检查订阅状态。"
---

要判断用户是否可以访问付费内容或查看付费墙，您需要在用户画像中检查其[访问等级](access-level)。

本文介绍如何访问用户画像状态，以决定向用户展示什么内容——是显示付费墙还是授予付费功能的访问权限。

## 获取订阅状态 \{#get-subscription-status\}

当您需要决定是否向用户显示付费墙或付费内容时，需要检查其用户画像中的[访问等级](access-level)。您有两种选择：

- 如果需要立即获取最新的用户画像数据（例如在应用启动时）或希望强制更新，请调用 `GetProfile`。
- 设置**自动用户画像更新**，以在订阅状态发生变化时自动刷新本地副本。

### 获取用户画像 \{#get-profile\}

获取订阅状态最简单的方法是使用 `GetProfile` 方法访问用户画像：

```csharp showLineNumbers
Adapty.GetProfile((profile, error) => {
  if (error != null) {
    // handle the error
    return;
  }

// check the access
});
```

### 监听订阅更新 \{#listen-to-subscription-updates\}

要在应用中自动接收用户画像更新：

1. 继承 `AdaptyEventListener` 并实现 `OnLoadLatestProfile` 方法——每当用户的订阅状态发生变化时，Adapty 会自动调用此方法。
2. 在该方法被调用时存储更新后的用户画像数据，以便在整个应用中使用，无需发起额外的网络请求。

```csharp
public class SubscriptionManager : MonoBehaviour, AdaptyEventListener {
    private AdaptyProfile currentProfile;
    
    void Start() {
        // Register this object as an Adapty event listener
        Adapty.SetEventListener(this);
    }
    
    // Store the profile when it updates
    public void OnLoadLatestProfile(AdaptyProfile profile) {
        currentProfile = profile;
        // Update UI, unlock content, etc.
    }
    
    public void OnInstallationDetailsSuccess(AdaptyInstallationDetails details) { }
    public void OnInstallationDetailsFail(AdaptyError error) { }
    
    // Use stored profile instead of calling getProfile()
    public bool HasAccess() {
        if (currentProfile?.AccessLevels != null && 
            currentProfile.AccessLevels.ContainsKey("premium")) {
            return currentProfile.AccessLevels["premium"].IsActive;
        }
        return false;
    }
}
```

:::note
每当应用启动时，Adapty 会自动调用 `OnLoadLatestProfile`，即使设备处于离线状态，也能提供缓存的订阅数据。
:::

## 将用户画像与付费墙逻辑关联 \{#connect-profile-with-paywall-logic\}

当您需要立即决定是否显示付费墙或授予付费功能访问权限时，可以直接检查用户的用户画像。此方法适用于以下场景：应用启动、进入付费区域，或在展示特定内容之前。

```csharp
private void CheckAccessLevel()
{
    Adapty.GetProfile((profile, error) => {
        if (error != null) {
            Debug.LogError("Error checking access level: " + error.Message);
            // Show paywall if access check fails
            return;
        }
        
        var accessLevel = profile.AccessLevels["YOUR_ACCESS_LEVEL"];
        if (accessLevel == null || !accessLevel.IsActive) {
            // Show paywall if no access
        }
    });
}

private void InitializePaywall()
{
    LoadPaywall();
    CheckAccessLevel();
}
``` 

## 后续步骤 \{#next-steps\}

现在您已了解如何追踪订阅状态，接下来请学习如何[使用用户画像](unity-quickstart-identify)，以确保用户能够访问其已付费的内容。