Inserting new lines and resizing font to fit into rectangle

I have a virtual rectangle of cardboard. On this some text is being “printed” by having a textmesh on top of it. The illusion is lost if text exceeds the limits of the cardboard.

Two parts:

  1. How do I - having assigned new text to it via script - automatically resize/change the font size - for it to always fit
  2. How do I make the Textmesh have linebreaks for it to fit within certain boundaries.

Basically I want to combine the two, so first the text should be fitted within the cardboard by linebreaks and if this isn’t enough it should be downsized.

I am using Javascript.

now firstly how large is the text? and how large is the piece of cardboard?, for this example im assuming the cardboard is 30cm x 30cm(1 ft x 1 ft) and you want to write “The Quick Brown Fox Jumped Over the Lazy Dog.”

because we in centimeters now, adjust the char size to 0.01

First how many characters are there? in this case there are 45. At size 36 we can get about 14(its not a lot, its barely two words) large characters on the board and 7 lines. but we need room for formatting so if we count to 14 and end up in a word we add the letter index we are up to i.e

The Quick Brown
Fox Jumped
//Brown is one letter too long so we push it down a line and add 4 to the total count

The Quick    //add 4 
Brown Fox   //add 4 again 
Jumped Over //add 2 
The Lazy Dog. 

// so it turns out we need 55 characters

so we can have up to 98 (7 lines x14 Characters) characters at size 36 so it will work.

  1. measure the size of the font and adjust accordingly 36 already worked for me.

    TextRenderer TR.size = 36

  2. you can add line breaks by adding the escape character
    to this string.

see here for string editing: String.Insert(Int32, String) Method (System) | Microsoft Learn

Its in C# I know, but its pretty easy to see how its written in UnityScript.

now you need to apply this logic to your code. I suggest Grouping the words into an array and have it count the word length on the spot and determine if it can fit on the line. i.e the sum of of the current word lengths must be equal or less then 14, or it will drop the last word to a new line. and start the count again starting from the length of the new word.

Ok Im going to leave you with this for you to absorb.

PS. Don’t Forget to Count the spaces.