Is there any way to get the position of a specific letter (or any part of the string) in a UI text? In World Space, Screen Space, Canvas Space, whatever.
Say I have text that can be “Level 1” or “Level 1000”. It’s middle-aligned so the letter L can be anywhere on the screen, but I want to move a GameObject right beside the L. How would I find that?
This is using Unity’s UI canvas. Specifically with Screen Space - Overlay, but ideally I’d like a solution that works regardless of screen space/world space type.
Hi Here is the scriptsnippet which will help you find exact letter position in Unity UI Text.
public class TextTest : MonoBehaviour
{
public Text textComp;
public int charIndex;
public Canvas canvas;
void PrintPos ()
{
string text = textComp.text;
if (charIndex >= text.Length)
return;
TextGenerator textGen = new TextGenerator (text.Length);
Vector2 extents = textComp.gameObject.GetComponent<RectTransform>().rect.size;
textGen.Populate (text, textComp.GetGenerationSettings (extents));
int newLine = text.Substring(0, charIndex).Split('
@Halleester, if you’re using this on a canvas with a canvas scaler component, you need to divide it by the scale factor. @hengde’s solution won’t actually work due to the canvas scaler being broken, canvas.scalefactor will always return 1 since it takes a frame to get the scale information.
To fix this store a variable that either gets defined after the scale value has initalized (one frame will do) or set it in an update function.