I tried to create a UI text with a grey semi-transparent background just fit the size of the text. But the problem is how can I know the size of the text? I tried counting characters but ‘m’ is longer than ‘n’ and font plays in a role too.
wwu39 39 show the full image of you UI
Two options I can think of. First, use TextMeshPro which has options to get width fairly easy.
Or, go with a contentSizeFitter component.
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-ContentSizeFitter.html
