Skip to content

Instantly share code, notes, and snippets.

@lynzrand
Created April 27, 2019 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lynzrand/31bcbc9e5e5c248e54692158e6ab364e to your computer and use it in GitHub Desktop.
Save lynzrand/31bcbc9e5e5c248e54692158e6ab364e to your computer and use it in GitHub Desktop.
Wrong Code - Determining a text's width in characters
public static Vector2Int GetConsoleSize(Text text)
{
text.font.RequestCharactersInTexture(" ", text.fontSize, text.fontStyle);
text.font.GetCharacterInfo(' ', out CharacterInfo info, text.fontSize, text.fontStyle);
var scaleFactor = text.canvas.scaleFactor;
float fontWidth = info.advance;
float fontHeight = text.fontSize * text.lineSpacing;
var rect = text.GetComponent<RectTransform>().rect;
float boundingBoxWidth = rect.xMax - rect.xMin;
float boundingBoxHeight = rect.yMax - rect.yMin;
int consoleWidth = Mathf.FloorToInt(boundingBoxWidth / fontWidth);
int consoleHeight = Mathf.FloorToInt(boundingBoxHeight / fontHeight);
if (consoleWidth < 0) consoleWidth = 0;
if (consoleHeight < 0) consoleHeight = 0;
return new Vector2Int(x: consoleWidth, y: consoleHeight);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment