Unity 遊戲中的好友

Play 遊戲的好友可讓玩家建立並維護一個橫跨遊戲的好友名單。您可以要求存取這份好友名單,讓玩家更能和好友一起玩您的遊戲。好友系統詳情請參閱好友概念頁面

事前準備

  • 設定專案和 Unity 專用 Google Play 遊戲外掛程式。詳情請參閱入門指南

  • 實作這些 API 的最佳方式說明請參閱最佳做法規範

實作這些 API 的最佳方式說明請參閱最佳做法規範

啟用好友

若要啟用好友,請用以下函式:

  • 檢視好友:要求存取某位玩家的好友名單,以便把對方的 Play 遊戲好友加入遊戲裡的好友名單。

  • 檢視玩家的個人資料:讓玩家可以檢視其他玩家的 Play 遊戲個人資料。這樣做才能讓玩家知道好友的身分,並能透過您的遊戲和其他 Play 遊戲玩家互動。您必須讓這個內容和某個 UI 元素連結,以便觸發彈出式視窗。詳情請參閱好友規範

檢視好友

載入好友的方式有兩種,您可以使用 ISocial 架構,或直接使用 PlayGamesPlatform

使用 ISocial 架構載入好友

Social.localUser.LoadFriends((success) =>  {
    Debug.Log("Friends loaded OK: " + ok));
    foreach(IUserProfile p in Social.localUser.friends) {
         Debug.Log(p.userName + " is a friend");
    }

不過,如果目前的玩家還沒授權讓遊戲存取這項資訊,那麼呼叫就會失敗。請用 GetLastLoadFriendsStatus 檢查 LoadFriends 是否因為缺少同意而導致失敗。

 PlayGamesPlatform.Instance.GetLastLoadFriendsStatus((status) => {
    // Check for consent
    if (status == LoadFriendsStatus.ResolutionRequired) {
        // Ask for resolution.
    }
});

遊戲可以藉由呼叫 AskForLoadFriendsResolution 要求目前玩家分享好友名單。

PlayGamesPlatform.Instance.AskForLoadFriendsResolution((result) => {
    if (result == UIStatus.Valid) {
        // User agreed to share friends with the game. Reload friends.
    } else {
        // User doesn’t agree to share the friends list.
    }
});

這段函式可以顯示該平台適用的好友分享 UI。這個 UI 會詢問玩家是否想要跟遊戲分享好友。

使用 PlayGamesPlatform 載入好友

您也可以使用 LoadFriendsLoadMoreFriends 載入好友:

PlayGamesPlatform.Instance.LoadFriends(pageSize, forceReload, (status) => {
    // Check if the call is successful and if there are more friends to load.
});

PlayGamesPlatform.Instance.LoadMoreFriends(pageSize, (status) => {
    // Check if there are more friends to load.
});

pageSize 參數代表要求本頁面的項目數量。請注意,如果系統內已有快取資料,則傳回的緩衝區所含的資料可能會超過這個大小。如果集合內含有足夠的記錄,那麼這個緩衝區保證會含有這個數量以上的項目。如果 forceReload 設定為 true,那麼這段呼叫會清除所有本機的快取資料,並嘗試擷取伺服器上的最新資料。這個的常見用途是使用者執行重新整理這類的操作。一般來說,這個項目應該設為 false,以便善用資料快取帶來的好處。

如果回呼回傳 LoadFriendsStatus.LoadMore,表示尚可載入更多好友。LoadFriendsStatus.ResolutionRequired 表示使用者並未分享好友名單,您可以直接呼叫 PlayGamesPlatform.Instance.AskForLoadFriendsResolution

判斷好友名單的瀏覽權限

請用 PlayGamesPlatform.Instance.GetFriendsListVisibility 檢查使用者是否已和遊戲分享好友名單。可能回傳的狀態有:

  • FriendsListVisibilityStatus.RequestRequired 表示您必須徵求同意。

  • FriendsListVisibilityStatus.Visible 表示好友名單應該已經載入成功。

  • FriendsListVisibilityStatus.Unknown 通常不應該發生。您可以把 forceReload 設為 true,以便重新整理資料。

PlayGamesPlatform.Instance.GetFriendsListVisibility(forceReload, (friendsListVisibilityStatus) => {});

檢視玩家個人資料

如果想新增或移除好友,請用顯示及比較個人資料函式。這個函式會觸發底部功能表對話方塊,並顯示該名使用者的 Play 遊戲個人資料,以及呼叫含有要求玩家 ID 的函式。如果玩家和好友在遊戲中都有設定暱稱,請在呼叫中使用這些暱稱,以便為個人資料 UI 加入更多背景資訊:

PlayGamesPlatform.Instance.ShowCompareProfileWithAlternativeNameHintsUI(
    mFirstFriendId, /* otherPlayerInGameName= */ null, /* currentPlayerInGameName= */ null,
    (result) => {
        // Profile comparison view has closed.
});