I have a Canvas (Render Mode = “World Space”, and its Rect Transform has Width = 4, Height = 2) with a Canvas Scaler with “Dynamic Pixels Per Unit” = 20. I have placed a UI Text in the canvas, and would like to know how large in absolute terms the text is in the virtual space. The text is set to Font Size = 12.
How should I calculate the absolute size of the text?
I am not sure I understand the relationship between the dynamic pixels per unit, the font size, the canvas size, and the absolute size of the text. Any help would be greatly appreciated.
I know it’s not exact, but this works for me for finding a rough size of GUI text:
static float getTextWidth(Canvas canvas, Text text, int length)
{
return text.fontSize * 0.5f * length * canvas.transform.localScale.x;
}
static float getTextHeight(Canvas canvas, Text text)
{
return text.fontSize * canvas.transform.localScale.y;
}
@benjaminoutram
The Following Code adjust the height of the text GameObject only! If you need to adjust the parent you will add the heightChange to the parents RectTransform too.
public class Example : MonoBehaviour {
public GameObject text;
public float wordWrapSpacing;
public void AdjustSize()
{
GUIStyle gui = new GUIStyle();
RectTransform textRect = text.getComponent<RectTransform>();
//This calculates the size needed to hold all of the text based on Font Size
Vector2 adjustmentSize = gui.CalcSize(text.getComponent<Text>().text);
//Adjust the wordWrapSpacing based on the font you are using.
float heightChange = size.y * (size.x / textRect.rect.width) + wordWrapSpacing * (size.x / textRect.rect.width);
//This is needed because your text might not have to be adjusted.
if(textRect.rect.height < heightChange)
{
textRect.sizeDelta = new Vector2(textRect.rect.width, textRect.rect.height + heightChange);
}
}//End Function
}//end Class
//Note If you are messing with both height and width you will need to multiply the wordWrapSpacing by the percentage change that has occurred width wise.
This is a very manual way of doing this and unity has many built in functions.