Unity calculate the size of a text box before text gets drawn so it can lerp to the next size

by BigDuke6   Last Updated August 13, 2019 22:13 PM - source

Im trying to make a dialog box image that lerps to the next size.

In order to do that I need to calculate the size of the image before the text gets drawn.

My idea is to use the legacy GUI stuff like guiStyle.CalcSize to get the width and guiStyle.CalcHeight to get the height. then im setting the image's layout elements min values = to the GUI sizes.

the width is set to the longest string in the array of "lines"

the problem is that while the image does scale it doesn't do so correctly. perhaps my approach is wrong and there's an easier way?

private void Update()
{
    lineText = dialogueRunner.dialogText;
    drawnText = dialogueUI.lineText.text;

    //Debug.Log(prefferedValues);

    numberOfCharactersInLine = dialogueRunner.dialogText.Length;


    lineTextWithNewLine = NewLineAfterNChar(lineText, 18);

    string[] lines = lineTextWithNewLine.Split(new[] { "\n" }, StringSplitOptions.None);
    for (int i = 0; i < lines.Length; i++)
    {
        longest = lines.OrderByDescending(s => s.Length).First();

        prefferedValues = textMesh.GetPreferredValues(longest);



        Debug.Log(longest.Length);
    }

    //scale isnt correct
    layoutElement.minWidth = size.x;
    layoutElement.minHeight = size.y;

}



void OnGUI()
{
    guiContent = new GUIContent(longest);

    guiStyle = GUI.skin.box;
    guiStyle.alignment = TextAnchor.UpperLeft;
    guiStyle.wordWrap = true;

    //------
    boxSize = new Rect(Screen.width / 2, Screen.height / 1, txtBGRect.sizeDelta.x, txtBGRect.sizeDelta.y);
    boxSize.center = new Vector2(Screen.width / 2, Screen.height / 2);

    // // Compute how large the button needs to be.
    size.x = guiStyle.CalcSize(guiContent).x;
    width = size.x / 1;
    size.y = guiStyle.CalcHeight(guiContent, width);
    height = size.y;

    GUI.Box(boxSize, longest); //this draws the box

}

//Pass it a string and it will insert a line break after every n characters at end of words.

public static string NewLineAfterNChar(string inputText, int lineLength)
{
    string[] stringSplit = inputText.Split(' ');//Split string into array seperatly "word1" "word2" "word3" etc...
    int charCounter = 0;
    string finalString = "";

    for (int i = 0; i < stringSplit.Length; i++)// iterates per word count
    {
        finalString += stringSplit[i] + " ";// "word1 "  "word2 " "word3 "
        charCounter += stringSplit[i].Length;

        if (charCounter > lineLength)//after n characters
        {
            finalString += "\n";
            charCounter = 0;
        }

    }
    return finalString;
}
Tags : unity c# gui


Related Questions


Unfortunately game has stopped

Updated July 02, 2019 11:13 AM

How to animate objects in Unity 3D

Updated July 12, 2015 13:05 PM