- Home /
Problem to position a GUIText centered at an object
Hi,
I'm trying to position a GUI text at an object. The text must be centered and to achieve this I have to get the text bounds as the target object bounds. I'm creating the GUIText on the fly (it is not a prefab). The picture below illustrates what suppose to be:
Rendered text is out of the object bounds, it's rendering aside the object not in its middle. I have tried to get the GUIText position using guiText.rendered.bounds.size.x
but didn't work, and now trying with guiText.GetScreenRect().width
and also not work at all.
Please, check out the part of the code:
//create a GUIText
go = new GameObject("FloatingText");
guiText = go.AddComponent(typeof(GUIText)) as GUIText;
//text properties
guiText.color = color;
guiText.fontSize = 16;
guiText.text = "100";
guiText.gameObject.AddComponent<DamageFloatingText>();
//position the GUIText at object's center
Vector3 objectPos = transform.position;
objectPos.y += upSize;
Debug.Log(transform.position.x);
float xPos = (transform.position.x - (guiText.GetScreenRect().width / 2));
objectPos.x = xPos;
Debug.Log("Width " + guiText.GetScreenRect().width);
Vector3 relativePosition = Camera.main.transform.InverseTransformPoint(objectPos);
relativePosition.z = Mathf.Max(relativePosition.z, 1.0f);
guiText.transform.position =
Camera.main.WorldToViewportPoint(Camera.main.transform.TransformPoint(relativePosition + Vector3.up));
xPost suppose to be the correct position to render the text.
Any clue or suggestion will be very helpful. Thanks in advance!
Answer by robertbu · Dec 14, 2013 at 02:52 PM
Not tested, but can't you just set GUIText.anchor to TextAnchor.MiddleCenter:
guiText.anchor = TextAnchor.MiddleCenter;
Thanks man, you're a genius. I wondering I have to do it only by my own.