using System.Collections.Generic; using TMPro; using UnityEngine; public class MessageBoxController : MonoBehaviour { public int maxMessageNum = 50; public string defaultColor = "white"; public string warningColor = "#ffa500ff"; public string errorColor = "#800000ff"; public string goodColor = "#00ff00ff"; public GameObject messagePanelObj; public GameObject messageTextPrefab; [SerializeField] private List messages = new List(); /// /// Pushes a simple message to the message list. /// /// The message text. /// /// This method pushes a simple text message to the message list and handles message overflow to ensure that the message list does not grow indefinitely. /// public void PushMessage(string text) { // push simple message to message list MessageOverflowHandler(); Message newMessage = new Message(); newMessage.text = text; GameObject newText = Instantiate(messageTextPrefab, messagePanelObj.transform); newMessage.textObject = newText.GetComponent(); newMessage.textObject.text = newMessage.text; messages.Add(newMessage); } /// /// Pushes multi-color messages to the message list. /// /// The list of message texts. /// The list of colors. /// /// This method pushes multi-color text messages to the message list and handles message overflow to ensure that the message list does not grow indefinitely. /// If the lengths of the message text list and the color list do not match, it either removes excess colors or adds white color to the extra messages. /// public void PushMessage(List messageList,List colorList) { // check messages and colors list length match if (messageList.Count != colorList.Count) { // delete extra colors or add white color to extra messages if (messageList.Count > colorList.Count) { while(messageList.Count > colorList.Count) { colorList.Add(defaultColor); } } else { colorList.RemoveRange(messageList.Count, colorList.Count - messageList.Count); } } MessageOverflowHandler(); Message newMessage = new Message(); newMessage.text = ""; // assemble message text with color for (int i = 0; i < messageList.Count; i++) { newMessage.text += "" + messageList[i] + ""; } GameObject newText = Instantiate(messageTextPrefab, messagePanelObj.transform); newMessage.textObject = newText.GetComponent(); newMessage.textObject.text = newMessage.text; messages.Add(newMessage); } [System.Serializable] public class Message { public string text; public TMPro.TextMeshProUGUI textObject; } private void MessageOverflowHandler() { // destroy the oldest message if message list is full if (messages.Count >= maxMessageNum) { Destroy(messages[0].textObject.gameObject); messages.RemoveAt(0); } } }