유니티 플레이팹 친구 추가, 삭제하기 Playfab Friends Add, Delete 간단 사용법

반응형

유니티 플레이팹 친구 추가, 삭제하기 Playfab Friends Add, Delete 간단 사용법

플레이팹 로그인이 되었다는 가정하에 진행

 

유니티 플레이팹 게스트 로그인 Playfab Sign In with Guest Login 간단 사용법

코드 작성 using PlayFab; using PlayFab.ClientModels; using PlayFab.Json; using PlayFab.ProfilesModels; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using EntityKey = PlayFab.ProfilesMod

parksh3641.tistory.com


코드 작성

using System;
using System.Collections.Generic;
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine;

// 친구 ID 타입 정의 (기존 코드에서 가져옴)
public enum FriendIdType
{
    PlayFabId,
    Username,
    Email,
    DisplayName
}

public class PlayfabManager : MonoBehaviour
{
    // 친구 목록 저장
    private List<FriendInfo> friendsList = new List<FriendInfo>();
    
    // 이벤트 시스템
    public event Action<List<FriendInfo>> OnFriendsListUpdated;
    public event Action<bool, string> OnFriendActionCompleted;
    
    // 프로퍼티 - 현재 친구 목록 접근
    public List<FriendInfo> Friends => new List<FriendInfo>(friendsList);
    
    // 에러 핸들러
    private void DisplayPlayfabError(PlayFabError error)
    {
        string errorMessage = "PlayFab 오류: " + error.GenerateErrorReport();
        Debug.LogError(errorMessage);
        OnFriendActionCompleted?.Invoke(false, errorMessage);
    }
    
    // 친구 목록 가져오기
    public void GetFriendList(bool includeFacebookFriends = true, bool includeSteamFriends = false)
    {
        Debug.Log("친구 목록 로드 중...");
        
        PlayFabClientAPI.GetFriendsList(
            new GetFriendsListRequest
            {
                IncludeSteamFriends = includeSteamFriends,
                IncludeFacebookFriends = includeFacebookFriends,
                ProfileConstraints = new PlayerProfileViewConstraints
                {
                    ShowDisplayName = true,
                    ShowStatistics = true,
                    ShowAvatarUrl = true,
                    ShowLastLogin = true
                },
                XboxToken = null
            },
            result => {
                friendsList = result.Friends ?? new List<FriendInfo>();
                
                Debug.Log($"친구 목록 로드 완료! 총 {friendsList.Count}명의 친구가 있습니다.");
                
                // 친구 정보 로깅
                foreach (var friend in friendsList)
                {
                    Debug.Log($"친구: {friend.TitleDisplayName ?? friend.Username ?? friend.FriendPlayFabId}");
                }
                
                // 이벤트 호출
                OnFriendsListUpdated?.Invoke(friendsList);
                OnFriendActionCompleted?.Invoke(true, "친구 목록 로드 완료");
            },
            DisplayPlayfabError
        );
    }
    
    // 친구 추가
    public void AddFriend(FriendIdType idType, string friendId)
    {
        if (string.IsNullOrEmpty(friendId))
        {
            Debug.LogWarning("친구 ID가 비어 있습니다.");
            OnFriendActionCompleted?.Invoke(false, "친구 ID가 비어 있습니다.");
            return;
        }
        
        Debug.Log($"친구 추가 시도 중: {friendId} (타입: {idType})");
        
        var request = new AddFriendRequest();
        
        // ID 타입에 따라 요청 설정
        switch (idType)
        {
            case FriendIdType.PlayFabId:
                request.FriendPlayFabId = friendId;
                break;
            case FriendIdType.Username:
                request.FriendUsername = friendId;
                break;
            case FriendIdType.Email:
                request.FriendEmail = friendId;
                break;
            case FriendIdType.DisplayName:
                request.FriendTitleDisplayName = friendId;
                break;
            default:
                Debug.LogError("지원되지 않는 친구 ID 타입입니다.");
                OnFriendActionCompleted?.Invoke(false, "지원되지 않는 친구 ID 타입");
                return;
        }
        
        PlayFabClientAPI.AddFriend(
            request,
            result => {
                Debug.Log("친구 추가 성공!");
                OnFriendActionCompleted?.Invoke(true, "친구 추가 성공");
                
                // 친구 목록 갱신
                GetFriendList();
            },
            error => {
                // 특별 오류 처리
                if (error.Error == PlayFabErrorCode.AccountNotFound)
                {
                    Debug.LogError("해당 ID의 사용자를 찾을 수 없습니다.");
                    OnFriendActionCompleted?.Invoke(false, "해당 ID의 사용자를 찾을 수 없습니다.");
                }
                else if (error.Error == PlayFabErrorCode.FriendAlreadyExists)
                {
                    Debug.LogWarning("이미 친구로 등록된 사용자입니다.");
                    OnFriendActionCompleted?.Invoke(false, "이미 친구로 등록된 사용자입니다.");
                }
                else
                {
                    DisplayPlayfabError(error);
                }
            }
        );
    }
    
    // 친구 삭제
    public void RemoveFriend(FriendInfo friendInfo)
    {
        if (friendInfo == null || string.IsNullOrEmpty(friendInfo.FriendPlayFabId))
        {
            Debug.LogWarning("유효하지 않은 친구 정보입니다.");
            OnFriendActionCompleted?.Invoke(false, "유효하지 않은 친구 정보");
            return;
        }
        
        string friendName = friendInfo.TitleDisplayName ?? friendInfo.Username ?? friendInfo.FriendPlayFabId;
        Debug.Log($"친구 삭제 시도 중: {friendName}");
        
        PlayFabClientAPI.RemoveFriend(
            new RemoveFriendRequest
            {
                FriendPlayFabId = friendInfo.FriendPlayFabId
            },
            result => {
                Debug.Log($"친구 삭제 성공: {friendName}");
                
                // 친구 목록 업데이트
                friendsList.Remove(friendInfo);
                
                OnFriendsListUpdated?.Invoke(friendsList);
                OnFriendActionCompleted?.Invoke(true, "친구 삭제 성공");
            },
            DisplayPlayfabError
        );
    }
    
    // PlayFab ID로 친구 삭제 (편의 메서드)
    public void RemoveFriendByPlayFabId(string playFabId)
    {
        if (string.IsNullOrEmpty(playFabId))
        {
            Debug.LogWarning("PlayFab ID가 비어 있습니다.");
            OnFriendActionCompleted?.Invoke(false, "PlayFab ID가 비어 있습니다.");
            return;
        }
        
        Debug.Log($"PlayFab ID로 친구 삭제 시도 중: {playFabId}");
        
        // 친구 목록에서 해당 ID 찾기
        FriendInfo friendToRemove = null;
        foreach (var friend in friendsList)
        {
            if (friend.FriendPlayFabId == playFabId)
            {
                friendToRemove = friend;
                break;
            }
        }
        
        if (friendToRemove != null)
        {
            RemoveFriend(friendToRemove);
        }
        else
        {
            Debug.LogWarning("해당 ID를 가진 친구를 찾을 수 없습니다.");
            OnFriendActionCompleted?.Invoke(false, "해당 ID를 가진 친구를 찾을 수 없습니다.");
        }
    }
    
    // 친구 목록 필터링 (닉네임으로 검색)
    public List<FriendInfo> SearchFriendsByName(string nameFilter)
    {
        if (string.IsNullOrEmpty(nameFilter))
        {
            return new List<FriendInfo>(friendsList);
        }
        
        List<FriendInfo> filteredList = new List<FriendInfo>();
        nameFilter = nameFilter.ToLower();
        
        foreach (var friend in friendsList)
        {
            string displayName = (friend.TitleDisplayName ?? "").ToLower();
            string username = (friend.Username ?? "").ToLower();
            
            if (displayName.Contains(nameFilter) || username.Contains(nameFilter))
            {
                filteredList.Add(friend);
            }
        }
        
        return filteredList;
    }
    
    // 친구 정보 가져오기
    public FriendInfo GetFriendByPlayFabId(string playFabId)
    {
        if (string.IsNullOrEmpty(playFabId))
        {
            return null;
        }
        
        foreach (var friend in friendsList)
        {
            if (friend.FriendPlayFabId == playFabId)
            {
                return friend;
            }
        }
        
        return null;
    }
}

 

반응형