Detect height overflow in UI Text

I’m using unity 5.1.1f1 and I have a scene with two UI texts side by side. These objects are filled with text by code, but I want to measure the height of the current UI text, and detect if it fits on the box. If it doesn’t I want to put that text into the other box.

I was trying to use LayoutUtility.GetPreferredHeight but still haven’t managed to achieve that.

Thanks in advance

In more recent versions of Unity (2019) and UI.Text, it looks like the new solution is TextGenerator.

Here is solution which I figured out by myself.

GUIStyle height_calculator = new GUIStyle();
GUIContent guiTextContent = new GUIContent(yourTextObj.GetComponent<Text>().text);
         
float textWidth = yourTextObj.GetComponent<Text>().preferredWidth;
float textHeight = height_calculator.CalcHeight(guiTextContent , textWidth);

Works well for me.