Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How to get a full character's width (including whitespace) in TextMeshPro?

Discussion in 'UGUI & TextMesh Pro' started by _eternal, Aug 5, 2022.

  1. _eternal

    _eternal

    Joined:
    Nov 25, 2014
    Posts:
    301
    I have some semi-functional code for a pretend-caret in TMP. Basically, I want an Image to appear at the end of a regular TextMeshProUGUI string (as opposed to an InputField). I'm doing it sort of like this.

    Code (CSharp):
    1. charInfo = textInfo.characterInfo[charIndex];
    2.  
    3. //start at the end of the previous character
    4. float targetLocalX = charInfo.bottomRight.x;
    5.  
    6. //add half of the caret's width
    7. targetLocalX += myRect.rect.width / 2f;
    8.  
    9. //add half the width of the previous char so that the caret appears beneath the upcoming char
    10. float width = charInfo.vertex_BR.position.x - charInfo.vertex_BL.position.x;
    11. targetLocalX += width / 2f;
    I'm doing this with a monospaced font, so you'd expect that each char would have the same width. However, the width float comes out different each time; I believe it's only accounting for the drawn character, rather than the full width (including space) of the character.

    Is there a way to obtain the latter information? I think that's all I need to get this to work.