Hello everyone!
I have a chat system already created (I receive the messages perfectly) but now I have to show them in a correct way.
I want to create an object with a text component and so show it, but I have some problems:
-
How do I determine the height of the text depending on the text written inside so I can create the following message just below?
-
How can I do to slide the scroll view up a suitable amount at the height of each text so that it shows just the new message?
So far, the only thing I have, and that does not work very well, is this: (Where “chatbox” is the “content” object that was created within the “viewport” within the scrollview)
GameObject go = new GameObject("Msg");
var text = go.AddComponent<UnityEngine.UI.Text>();
var layout = go.AddComponent<UnityEngine.UI.LayoutElement>();
layout.minHeight = 40f;
var recttransform = go.GetComponent<RectTransform>();
go.transform.SetParent(chatBox);
messages.AddLast(go);
//text
text.text = "<color=" + nameColor + "><b>" + userName + "</b></color>" + ": " + msgString;
text.color = Color.black;
text.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
Debug.Log(text.text);
//size
recttransform.sizeDelta = new Vector2(400, text.preferredHeight);
//position
if (lastMessage != null)
{
recttransform.position = lastMessage.GetComponent<Transform>().position;
recttransform.Translate(new Vector2(0, -lastMessage.GetComponent<RectTransform>().sizeDelta.y));
}
else
{
recttransform.position = chatBox.position;
recttransform.Translate(new Vector2(recttransform.sizeDelta.x / 2, -recttransform.sizeDelta.y / 2));
}
//move chatbox
//scrollRect.velocity = new Vector2(0, 40f);
//lastMessage
lastMessage = go;
Thank you in advance for your help.
Greetings.
