Skip to content

Instantly share code, notes, and snippets.

@LukmanaAfif
Created January 8, 2021 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LukmanaAfif/8bb4a5a355f08b188c3de3f44db40977 to your computer and use it in GitHub Desktop.
Save LukmanaAfif/8bb4a5a355f08b188c3de3f44db40977 to your computer and use it in GitHub Desktop.
AccelByte Sample Game Unity - Lobby, Party, and Chat Logic
#region AccelByte Chat Functions
public void SendChatMessage()
{
if (string.IsNullOrEmpty(UIHandlerLobbyComponent.messageInputField.text))
WriteWarningInChatBox("Please enter write your message");
else if (string.IsNullOrEmpty(activePlayerChatUserId))
WriteWarningInChatBox("Please select player or party to chat");
else if (!UIHandlerLobbyComponent.partyChatButton.interactable)
SendPartyChat();
else
{
SendPersonalChat(activePlayerChatUserId);
}
}
/// <summary>
/// Send a party chat if the player is in a party
/// </summary>
private void SendPartyChat()
{
lobbyLogic.abLobby.SendPartyChat(UIHandlerLobbyComponent.messageInputField.text, OnSendPartyChat);
}
/// <summary>
/// Send a personal chat to a friend
/// </summary>
/// <param name="userId"> required user id to chat with </param>
private void SendPersonalChat(string userId)
{
lobbyLogic.abLobby.SendPersonalChat(userId, UIHandlerLobbyComponent.messageInputField.text, OnSendPersonalChat);
}
public void ClearChatBoxUIPrefabs()
{
if (UIHandlerLobbyComponent.chatBoxScrollContent.childCount > 0)
{
for (int i = 0; i < UIHandlerLobbyComponent.chatBoxScrollContent.childCount; i++)
{
Destroy(UIHandlerLobbyComponent.chatBoxScrollContent.GetChild(i).gameObject);
}
}
}
public void ClearPlayerChatListUIPrefabs()
{
if (UIHandlerLobbyComponent.playerChatScrollContent.childCount > 0)
{
for (int i = 0; i < UIHandlerLobbyComponent.playerChatScrollContent.childCount; i++)
{
Destroy(UIHandlerLobbyComponent.playerChatScrollContent.GetChild(i).gameObject);
}
}
}
internal void RefreshDisplayNamePrivateChatListUI()
{
ClearPlayerChatListUIPrefabs();
foreach (var friend in lobbyLogic.friendsLogic.GetFriendList())
{
PlayerChatPrefab playerChatPrefab = Instantiate(UIHandlerLobbyComponent.playerChatPrefab, Vector3.zero, Quaternion.identity).GetComponent<PlayerChatPrefab>();
playerChatPrefab.transform.SetParent(UIHandlerLobbyComponent.playerChatScrollContent, false);
playerChatPrefab.GetComponent<PlayerChatPrefab>().SetupPlayerChatUI(friend.Value.DisplayName, friend.Value.UserId, friend.Value.IsOnline == "1");
playerChatPrefab.GetComponent<PlayerChatPrefab>().activePlayerButton.onClick.AddListener(() => OpenPrivateChatBox(friend.Value.UserId));
if (!string.IsNullOrEmpty(activePlayerChatUserId) && friend.Value.UserId == activePlayerChatUserId)
{
playerChatPrefab.GetComponent<PlayerChatPrefab>().backgroundImage.SetActive(true);
}
UIHandlerLobbyComponent.friendScrollView.Rebuild(CanvasUpdate.Layout);
}
}
internal void RefreshDisplayNamePartyChatListUI()
{
ClearPlayerChatListUIPrefabs();
foreach (var partyMember in lobbyLogic.partyLogic.GetAbPartyInfo().members)
{
var myUserData = accelByteManager.AuthLogic.GetUserData();
if (lobbyLogic.partyLogic.GetPartyMemberList().ContainsKey(partyMember) || partyMember == myUserData.userId)
{
PlayerChatPrefab playerChatPrefab = Instantiate(UIHandlerLobbyComponent.playerChatPrefab, Vector3.zero, Quaternion.identity).GetComponent<PlayerChatPrefab>();
playerChatPrefab.transform.SetParent(UIHandlerLobbyComponent.playerChatScrollContent, false);
if (partyMember != myUserData.userId && !string.IsNullOrEmpty(lobbyLogic.partyLogic.GetPartyMemberList()[partyMember].PlayerName))
{
playerChatPrefab.GetComponent<PlayerChatPrefab>().SetupPlayerChatUI(lobbyLogic.partyLogic.GetPartyMemberList()[partyMember].PlayerName, partyMember, true);
playerChatPrefab.GetComponent<PlayerChatPrefab>().activePlayerButton.interactable = false;
if (partyMember == lobbyLogic.partyLogic.GetAbPartyInfo().leaderID)
{
playerChatPrefab.GetComponent<PlayerChatPrefab>().SetupPartyLeader(lobbyLogic.partyLogic.GetPartyMemberList()[partyMember].PlayerName);
}
}
else if (partyMember == myUserData.userId)
{
playerChatPrefab.GetComponent<PlayerChatPrefab>().SetupPlayerChatUI(myUserData.displayName, myUserData.userId, true);
playerChatPrefab.GetComponent<PlayerChatPrefab>().activePlayerButton.interactable = false;
if (partyMember == lobbyLogic.partyLogic.GetAbPartyInfo().leaderID)
{
playerChatPrefab.GetComponent<PlayerChatPrefab>().SetupPartyLeader(myUserData.displayName);
}
}
UIHandlerLobbyComponent.friendScrollView.Rebuild(CanvasUpdate.Layout);
}
}
}
private void RefreshChatBoxUI()
{
ClearChatBoxUIPrefabs();
if (chatBoxList[activePlayerChatUserId].message.Count > 0)
{
for (int i = 0; i < chatBoxList[activePlayerChatUserId].message.Count; i++)
{
ChatMessagePrefab chatPrefab = Instantiate(UIHandlerLobbyComponent.chatBoxPrefab, Vector3.zero, Quaternion.identity).GetComponent<ChatMessagePrefab>();
chatPrefab.transform.SetParent(UIHandlerLobbyComponent.chatBoxScrollContent, false);
bool isMe = chatBoxList[activePlayerChatUserId].sender[i] == accelByteManager.AuthLogic.GetUserData().userId;
if (isMe)
{
chatPrefab.GetComponent<ChatMessagePrefab>().WriteMessage("You", chatBoxList[activePlayerChatUserId].message[i], isMe);
}
else
{
string playerChatName = lobbyLogic.friendsLogic.GetFriendList()[chatBoxList[activePlayerChatUserId].sender[i]].DisplayName;
chatPrefab.GetComponent<ChatMessagePrefab>().WriteMessage(playerChatName, chatBoxList[activePlayerChatUserId].message[i], isMe);
}
UIHandlerLobbyComponent.friendScrollView.Rebuild(CanvasUpdate.Layout);
}
}
}
private void WriteWarningInChatBox(string message)
{
ChatMessagePrefab chatPrefab = Instantiate(UIHandlerLobbyComponent.chatBoxPrefab, Vector3.zero, Quaternion.identity).GetComponent<ChatMessagePrefab>();
chatPrefab.transform.SetParent(UIHandlerLobbyComponent.chatBoxScrollContent, false);
chatPrefab.GetComponent<ChatMessagePrefab>().WriteWarning(message);
UIHandlerLobbyComponent.friendScrollView.Rebuild(CanvasUpdate.Layout);
}
public void OpenEmptyChatBox()
{
ClearChatBoxUIPrefabs();
ClearPlayerChatListUIPrefabs();
UIHandlerLobbyComponent.privateChatButton.interactable = false;
UIHandlerLobbyComponent.partyChatButton.interactable = true;
lobbyLogic.friendsLogic.LoadFriendsList();
}
public void OpenPrivateChatBox(string userId)
{
activePlayerChatUserId = userId;
if (!chatBoxList.ContainsKey(activePlayerChatUserId))
{
chatBoxList.Add(activePlayerChatUserId, new ChatData(activePlayerChatUserId, new List<string>(), new List<string>()));
}
RefreshDisplayNamePrivateChatListUI();
RefreshChatBoxUI();
}
public void OpenPartyChatBox()
{
if (lobbyLogic.partyLogic.GetPartyMemberList().Count > 0)
{
activePlayerChatUserId = "party";
if (!chatBoxList.ContainsKey(activePlayerChatUserId))
{
chatBoxList.Add(activePlayerChatUserId, new ChatData(activePlayerChatUserId, new List<string>(), new List<string>()));
}
RefreshChatBoxUI();
RefreshDisplayNamePartyChatListUI();
}
else
{
UIHandlerLobbyComponent.privateChatButton.interactable = false;
UIHandlerLobbyComponent.partyChatButton.interactable = true;
if (lobbyLogic.partyLogic.GetIsLocalPlayerInParty())
{
WriteWarningInChatBox("You don't have any party member");
}
else
{
WriteWarningInChatBox("You don't have any party");
}
}
}
public void ClearActivePlayerChat()
{
activePlayerChatUserId = null;
}
#endregion
#region AccelByte Lobby Functions
public void ConnectToLobby()
{
// Reset lobby to prevent dual session callback
// Each time user connect to lobby after login, it needs to renew the lobby.
abLobby = new Lobby(AccelBytePlugin.Config.LobbyServerUrl, new WebSocket(), new LobbyApi(AccelBytePlugin.Config.BaseUrl, new UnityHttpWorker()), AccelBytePlugin.GetUser().Session, AccelBytePlugin.Config.Namespace, new CoroutineRunner());
// Establish connection to the lobby service
abLobby.Connect();
if (abLobby.IsConnected)
{
//If we successfully connected, load our friend list.
Debug.Log("Successfully Connected to the AccelByte Lobby Service");
abLobby.SetUserStatus(UserStatus.Availabe, "OnLobby", OnSetUserStatus);
friendsLogic.ClearFriendList();
SetupLobbyUI();
}
else
{
//If we don't connect Retry.
// TODO: use coroutine to day the call to avoid spam
Debug.LogWarning("Not Connected To Lobby. Attempting to Connect...");
ConnectToLobby();
}
}
public void OnLogoutButtonClicked()
{
UIElementHandler.ShowLoadingPanel();
// Clean lobby state
if (abLobby.IsConnected)
{
OnExitFromLobby(AccelByteManager.Instance.AuthLogic.Logout);
}
else
{
AccelByteManager.Instance.AuthLogic.Logout();
}
CleanupLobbyUI();
}
private void CleanupLobbyUI()
{
// Clean lobby UI
matchmakingLogic.CleanupMatchmakingUI();
partyLogic.CleanupPartyUI();
UnsubscribeAllCallbacks();
}
private void SetupLobbyUI()
{
abLobby.SetUserStatus(UserStatus.Availabe, "OnLobby", OnSetUserStatus);
friendsLogic.LoadFriendsList();
SetupGeneralCallbacks();
friendsLogic.SetupFriendCallbacks();
chatLogic.SetupChatCallbacks();
matchmakingLogic.SetupMatchmakingCallbacks();
partyLogic.SetupPartyCallbacks();
partyLogic.SetupPartyUI();
SetupPlayerInfoBox();
}
private void SetupPlayerInfoBox()
{
UserData data = AccelByteManager.Instance.AuthLogic.GetUserData();
UIHandlerLobbyComponent.PlayerDisplayNameText.GetComponent<Text>().text = data.displayName;
}
private void SetupGeneralCallbacks()
{
abLobby.OnNotification += result => OnNotificationReceived(result);
abLobby.Disconnected += OnDisconnectNotificationReceived;
}
private void UnsubscribeAllCallbacks()
{
abLobby.Disconnected -= OnDisconnectNotificationReceived;
matchmakingLogic.UnsubscribeAllCallbacks();
partyLogic.UnsubscribeAllCallbacks();
friendsLogic.UnsubscribeAllCallbacks();
chatLogic.UnsubscribeAllCallbacks();
}
#endregion // AccelByte Lobby Functions
#region AccelByte Party Functions
/// <summary>
/// Create party lobby service
/// </summary>
/// <param name="callback"> callback result that includes party info </param>
private void CreateParty(ResultCallback<PartyInfo> callback)
{
lobbyLogic.abLobby.CreateParty(callback);
}
/// <summary>
/// Create party if not in a party yet
/// then invite a friend to the party
/// </summary>
/// <param name="userId"> required userid from the friend list </param>
public void CreateAndInvitePlayer(string userId)
{
if (!GetIsLocalPlayerInParty())
{
lobbyLogic.abLobby.CreateParty(OnPartyCreated);
}
else
{
isReadyToInviteToParty = true;
}
StartCoroutine(WaitForInviteToParty(userId));
}
IEnumerator WaitForInviteToParty(string userID)
{
bool isActive = true;
while (isActive)
{
yield return new WaitForSecondsRealtime(1.0f);
if (isReadyToInviteToParty)
{
InviteToParty(userID, OnInviteParty);
isReadyToInviteToParty = isActive = false;
}
}
}
/// <summary>
/// Invite a friend to a party
/// </summary>
/// <param name="id"> required userid to invite </param>
/// <param name="callback"> callback result </param>
public void InviteToParty(string id, ResultCallback callback)
{
string invitedPlayerId = id;
lobbyLogic.abLobby.InviteToParty(invitedPlayerId, callback);
}
/// <summary>
/// Kick party member from a party
/// hide popup party UI
/// </summary>
/// <param name="id"> required userid to kick </param>
public void KickPartyMember(string id)
{
lobbyLogic.abLobby.KickPartyMember(id, OnKickPartyMember);
HidePopUpPartyControl();
}
/// <summary>
/// Leave a party
/// hide popup party UI clear UI chat
/// </summary>
private void LeaveParty()
{
lobbyLogic.abLobby.LeaveParty(OnLeaveParty);
HidePopUpPartyControl();
lobbyLogic.chatLogic.ClearActivePlayerChat();
lobbyLogic.chatLogic.OpenEmptyChatBox();
}
/// <summary>
/// Get party info that has party id
/// Party info holds the party leader user id and the members user id
/// </summary>
private void GetPartyInfo()
{
lobbyLogic.abLobby.GetPartyInfo(OnGetPartyInfo);
}
/// <summary>
/// Get party member info to get the display name
/// </summary>
/// <param name="friendId"></param>
private void GetPartyMemberInfo(string friendId)
{
AccelBytePlugin.GetUser().GetUserByUserId(friendId, OnGetPartyMemberInfo);
}
private void ClearPartySlots()
{
// Clear the party slot buttons
for (int i = 0; i < UIHandlerLobbyComponent.partyMemberButtons.Length; i++)
{
UIHandlerLobbyComponent.partyMemberButtons[i].GetComponent<PartyPrefab>().OnClearProfileButton();
UIHandlerLobbyComponent.partyMemberButtons[i].GetComponent<Button>().onClick.AddListener(() => lobbyLogic.UIElementHandler.ShowExclusivePanel(ExclusivePanelType.FRIENDS));
}
partyMemberList.Clear();
}
private void RefreshPartySlots()
{
if (partyMemberList.Count > 0)
{
int j = 0;
foreach (KeyValuePair<string, PartyData> member in partyMemberList)
{
Debug.Log("RefreshPartySlots Member names entered: " + member.Value.PlayerName);
UIHandlerLobbyComponent.partyMemberButtons[j].GetComponent<Button>().onClick.RemoveAllListeners();
UIHandlerLobbyComponent.partyMemberButtons[j].GetComponent<PartyPrefab>().OnClearProfileButton();
UIHandlerLobbyComponent.partyMemberButtons[j].GetComponent<PartyPrefab>().SetupPlayerProfile(member.Value, abPartyInfo.leaderID);
j++;
}
if (lobbyLogic.chatLogic.activePlayerChatUserId == partyUserId)
{
lobbyLogic.chatLogic.RefreshDisplayNamePartyChatListUI();
}
}
lobbyLogic.friendsLogic.RefreshFriendsUI();
}
private void HidePopUpPartyControl()
{
UIHandlerLobbyComponent.popupPartyControl.gameObject.SetActive(false);
}
private void OnClosePartyInfoButtonClicked()
{
HidePopUpPartyControl();
}
/// <summary>
/// Accept party invitation by calling join party
/// require abPartyInvitation from callback party invitation event
/// </summary>
private void OnAcceptPartyClicked()
{
if (abPartyInvitation != null)
{
lobbyLogic.abLobby.JoinParty(abPartyInvitation.partyID, abPartyInvitation.invitationToken, OnJoinedParty);
}
else
{
Debug.Log("OnJoinPartyClicked Join party failed abPartyInvitation is null");
}
}
private void OnDeclinePartyClicked()
{
Debug.Log("OnDeclinePartyClicked Join party failed");
}
private void OnPlayerPartyProfileClicked()
{
// If in a party then show the party control menu party leader can invite, kick and leave the party.
// party member only able to leave the party.
if (GetIsLocalPlayerInParty())
{
// Remove listerner before closing
if (UIHandlerLobbyComponent.popupPartyControl.gameObject.activeSelf)
{
lobbyLogic.memberCommand.GetComponentInChildren<Button>().onClick.RemoveAllListeners();
}
UIHandlerLobbyComponent.popupPartyControl.gameObject.SetActive(!UIHandlerLobbyComponent.popupPartyControl.gameObject.activeSelf);
}
}
private List<PartyData> GetMemberPartyData()
{
List<PartyData> partyMemberData = new List<PartyData>();
if (partyMemberList.Count > 0)
{
foreach (KeyValuePair<string, PartyData> member in partyMemberList)
{
partyMemberData.Add(member.Value);
}
}
return partyMemberData;
}
private void OnLeavePartyButtonClicked()
{
if (accelByteManager.AuthLogic.GetUserData().userId == abPartyInfo.leaderID)
{
lobbyLogic.localLeaderCommand.gameObject.SetActive(false);
}
else
{
lobbyLogic.localmemberCommand.gameObject.SetActive(false);
}
UIHandlerLobbyComponent.popupPartyControl.gameObject.SetActive(false);
LeaveParty();
}
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment