SanAndreasUnity/Assets/Scripts/UI/ChatDisplay.cs

78 lines
2.1 KiB
C#
Raw Normal View History

2019-11-16 14:53:14 +00:00
using System.Collections.Generic;
using UnityEngine;
using SanAndreasUnity.Utilities;
2020-04-25 22:16:48 +00:00
using UnityEngine.UI;
using System.Linq;
2021-02-28 20:15:27 +00:00
using System.Text;
2019-11-16 14:53:14 +00:00
namespace SanAndreasUnity.UI
{
public class ChatDisplay : MonoBehaviour
{
Queue<Chat.ChatMessage> m_chatMessages = new Queue<Chat.ChatMessage>();
public int maxNumChatMessages = 5;
2019-11-16 16:09:43 +00:00
public float timeToRemoveMessage = 3f;
2019-11-16 14:53:14 +00:00
2021-02-28 20:15:27 +00:00
public Text chatText;
StringBuilder _stringBuilder = new StringBuilder();
2019-11-16 14:53:14 +00:00
void Start()
{
2021-02-27 22:17:56 +00:00
if (!F.IsInHeadlessMode)
Chat.ChatManager.onChatMessage += OnChatMsg;
2019-11-16 14:53:14 +00:00
}
void OnChatMsg(Chat.ChatMessage chatMsg)
{
if (m_chatMessages.Count >= this.maxNumChatMessages)
m_chatMessages.Dequeue();
m_chatMessages.Enqueue(chatMsg);
2019-11-16 16:09:43 +00:00
if (!this.IsInvoking(nameof(RemoveMessage)))
this.Invoke(nameof(RemoveMessage), this.timeToRemoveMessage);
2020-04-25 22:16:48 +00:00
this.UpdateUI();
2019-11-16 14:53:14 +00:00
}
2019-11-16 16:09:43 +00:00
void RemoveMessage()
{
if (m_chatMessages.Count > 0)
m_chatMessages.Dequeue();
// invoke again if there are more messages
if (m_chatMessages.Count > 0)
this.Invoke(nameof(RemoveMessage), this.timeToRemoveMessage);
2020-04-25 22:16:48 +00:00
this.UpdateUI();
2019-11-16 16:09:43 +00:00
}
2020-04-25 22:16:48 +00:00
void UpdateUI()
2019-11-16 14:53:14 +00:00
{
2021-02-28 20:15:27 +00:00
_stringBuilder.Clear();
_stringBuilder.EnsureCapacity(m_chatMessages.Count * 100);
foreach (var chatMessage in m_chatMessages)
2020-04-25 22:16:48 +00:00
{
2021-02-28 20:15:27 +00:00
GetDisplayTextForChatMessage(chatMessage, _stringBuilder);
2020-04-25 22:16:48 +00:00
}
2019-11-16 14:53:14 +00:00
2021-02-28 20:15:27 +00:00
this.chatText.text = _stringBuilder.ToString();
2019-11-16 14:53:14 +00:00
}
2021-02-28 20:15:27 +00:00
void GetDisplayTextForChatMessage(Chat.ChatMessage chatMessage, StringBuilder stringBuilder)
2020-04-25 22:16:48 +00:00
{
2021-03-01 00:24:21 +00:00
if (string.IsNullOrEmpty(chatMessage.sender))
stringBuilder.AppendFormat("{0}\n", chatMessage.msg);
else
stringBuilder.AppendFormat("<color=blue>{0}</color> : {1}\n", chatMessage.sender, chatMessage.msg);
2020-04-25 22:16:48 +00:00
}
2019-11-16 14:53:14 +00:00
}
}