Problems handling Scroll View for a simple chat

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.

@MaanuRP , I would try a Vertical Layout Group on a panel. The layout group will automatically space objects added to it. Here is an example using three messages that each a Text game object. Using this approach you don’t have to worry about positioning the text, just add it to the parent panel.

I can not believe that I did not think of it, with that I solve all my problems, thank you very much!