Skip to main content

Use the SDK to find players - Search for players - (Unity module)

Last updated on December 13, 2024

Unwrap the wrapper

In this tutorial, you will learn how to find players by their display name or friend code using the AccelByte Gaming Services (AGS) Game SDK. In Byte Wars, there is an SDK wrapper called FriendsEssentialsWrapper.cs. This wrapper contains functionalities related to player lookups. In this tutorial, you will use the starter version of that wrapper so you can implement friends functionalities to your liking.

What's in the Starter Pack

To follow this tutorial, find the starter version of the friends essentials wrapper called FriendsEssentialsWrapper_Starter. This class contains several functionalities already implemented. You will add more functionalities to this class to complete the player search feature.

  • FriendsEssentialsWrapper_Starter file: /Assets/Resources/Modules/FriendsEssentials/Scripts/FriendEssentialsWrapper_Starter.cs

The FriendsEssentialsWrapper_Starter class has several functionalities already:

  • The AGS Game SDK classes to get the details of players are User, Lobby, and UserProfiles. You can find these lines of code in FriendsEssentialsWrapper_Starter:

    private static ApiClient ApiClient => AccelByteSDK.GetClientRegistry().GetApi();
    private User user;
    private UserProfiles userProfiles;
    private Lobby lobby;
  • A property to store the player's user ID is declared as follows:

    public string PlayerUserId { get; private set; }
  • A property to store the current player's friend code:

    public string PlayerFriendCode { get; private set; } = string.Empty;
  • Static delegates to let another class assign their own logic to it:

    public static event Action<string> OnIncomingRequest = delegate { };
    public static event Action<string> OnRequestCanceled = delegate { };
    public static event Action<string> OnRequestRejected = delegate { };
    public static event Action<string> OnRequestAccepted = delegate { };
    public static event Action<string> OnUnfriended = delegate { };
  • An ObservableList property to let other object knows when the player's friend list have changed or when searching a player and let them do something in response.

    public ObservableList<string> CachedFriendUserIds { get; private set; } = new ObservableList<string>();
  • The Awake() function is used to get the user, user profiles, and lobby from the SDK. It also listens to the OnUserProfileReceived event from the Auth Essentials and Single Platform Auth modules' wrapper classes.

    private void Awake()
    {
    user = ApiClient.GetUser();
    userProfiles = ApiClient.GetUserProfiles();
    lobby = ApiClient.GetLobby();

    // Assign to both starter and non to make sure we support mix matched modules starter mode
    AuthEssentialsWrapper.OnUserProfileReceived += SetPlayerInfo;
    SinglePlatformAuthWrapper.OnUserProfileReceived += SetPlayerInfo;
    AuthEssentialsWrapper_Starter.OnUserProfileReceived += SetPlayerInfo;
    SinglePlatformAuthWrapper_Starter.OnUserProfileReceived += SetPlayerInfo;
    }
  • A helper function to cache the logged-in player's user ID and friend code:

    private void SetPlayerInfo(UserProfile userProfile)
    {
    PlayerUserId = userProfile.userId;
    PlayerFriendCode = userProfile.publicId;
    }

Implement Search Player by Friend Code

In this section, you will implement functionality to find players by their friend code.

  1. Open FriendsEssentialsWrapper_Starter.cs and create a new function called GetUserByFriendCode(). The SDK function used here returns PublicUserProfile instead of PublicUserData, but we need data that is present in the later. Hence, GetUserByUserId called at the end to get those data. We are also adding the target user to CachedFriendUserIds, to notify other object that the local player is currently searching for that user.

    public void GetUserByFriendCode(string friendCode, ResultCallback<PublicUserData> resultCallback)
    {
    userProfiles.GetUserProfilePublicInfoByPublicId(friendCode, result =>
    {
    if (result.IsError)
    {
    BytewarsLogger.LogWarning("Error getting user profile public info by public id, " +
    $"Error Code: {result.Error.Code} Error Message: {result.Error.Message}");

    resultCallback?.Invoke(Result<PublicUserData>.CreateError(result.Error.Code, result.Error.Message));

    return;
    }

    BytewarsLogger.Log("Successfully retrieved user profile public info by public id.");
    CachedFriendUserIds.Add(result.Value.userId);

    GetUserByUserId(result.Value.userId, resultCallback);
    });
    }
  2. Create a new function called GetUserByUserId() to get the user by user ID. This function is used to retrieve a more complete user data.

    private void GetUserByUserId(string userId, ResultCallback<PublicUserData> resultCallback)
    {
    user.GetUserByUserId(userId, result =>
    {
    if (result.IsError)
    {
    BytewarsLogger.LogWarning("Error getting user by user id, " +
    $"Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
    }
    else
    {
    BytewarsLogger.Log("Successfully retrieved user by user id.");
    }

    resultCallback?.Invoke(result);
    });
    }
  3. Create a new function called GetFriendshipStatus() to get the friendship status. As the name suggest, this is used to retrieve the friendship status of a player with the local player.

    public void GetFriendshipStatus(string userId, ResultCallback<FriendshipStatus> resultCallback)
    {
    lobby.GetFriendshipStatus(userId, result =>
    {
    if (result.IsError)
    {
    BytewarsLogger.LogWarning("Error getting friendship status, " +
    $"Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
    }
    else
    {
    BytewarsLogger.Log($"Successfully retrieved friendship status for {userId}");
    }

    resultCallback.Invoke(result);
    });
    }

Implement Search Player by Display Name

In this section, you will implement functionality to find players by their display name.

  1. Open FriendsEssentialsWrapper_Starter.cs and create a new function called GetUserByDisplayName(). In Byte Wars, only one search result is allowed. Hence, only the first result is taken in this function. The target user will also be added to CachedFriendUserIds to notify other object that the local player is currently searching for that user.

    info

    The backend can only accept three to 20 characters in length (inclusive) to perform a display name search. Any input outside this range will return no results. However, AGS Private Cloud users can modify the keyword character range by configuring their environment variable.

    API reference: IAM/PublicSearchUserV3

    public void GetUserByExactDisplayName(string displayName, ResultCallback<PublicUserInfo> resultCallback)
    {
    const SearchType searchBy = SearchType.DISPLAYNAME;

    user.SearchUsers(displayName, searchBy, result =>
    {
    if (result.IsError)
    {
    BytewarsLogger.LogWarning("Error searching users by display name, " +
    $"Error Code: {result.Error.Code} Error Message: {result.Error.Message}");

    resultCallback?.Invoke(Result<PublicUserInfo>.CreateError(result.Error.Code, result.Error.Message));
    return;
    }

    PublicUserInfo userByExactDisplayName = result.Value.data.FirstOrDefault(publicUserInfo =>
    publicUserInfo.displayName.Equals(displayName, StringComparison.CurrentCultureIgnoreCase));

    if (userByExactDisplayName == null)
    {
    BytewarsLogger.LogWarning($"User with display name {displayName} not found.");

    resultCallback?.Invoke(Result<PublicUserInfo>.CreateError(ErrorCode.UserNotFound, "User not found."));
    return;
    }

    BytewarsLogger.Log($"Successfully found users for display name: {displayName}");
    CachedFriendUserIds.Add(userByExactDisplayName.userId);

    resultCallback?.Invoke(Result<PublicUserInfo>.CreateOk(userByExactDisplayName));
    });
    }

Implement retrieving avatars

The data gathered from the previous functions are the player's avatar URL, not the image itself. To retrieve the actual image, another function from the SDK must be called. Follow these steps:

  1. Open FriendsEssentialsWrapper_Starter.cs and create a new function called GetUserAvatar().

    public void GetUserAvatar(string userId, ResultCallback<Texture2D> resultCallback)
    {
    user.GetUserAvatar(userId, result =>
    {
    if (result.IsError)
    {
    BytewarsLogger.LogWarning("Error getting Avatar, " +
    $"Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
    }
    else
    {
    BytewarsLogger.Log($"Successfully retrieved Avatar for User Id: {userId}");
    }

    resultCallback?.Invoke(result);
    });
    }

Implement sending friend requests

To implement the functionality to send friend invitation requests, open FriendsEssentialsWrapper_Starter.cs and create a new function called SendFriendRequest().

public void SendFriendRequest(string userId, ResultCallback resultCallback)
{
lobby.RequestFriend(userId, result =>
{
if (result.IsError)
{
BytewarsLogger.LogWarning("Error sending Friends Request, " +
$"Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
}
else
{
BytewarsLogger.Log("Successfully sent Friends Request");
}

resultCallback?.Invoke(result);
});
}

Resources