I am trying to find a way better to have a prefab with a GUIText. Because GUIText transform are relative to screen and must always be in absolute coordinates, I need to force its position every frame. Is it correct?
Test code:
function Update() {
var pos = Camera.main.WorldToScreenPoint(transform.Find("TextPosition").transform.position);
var gui = FindComponentInChildren(GUIText);
gui.transform.position = Vector3.zero;
gui.pixelOffset = pos;
}
[Edited]
Another option is dynamically create the GuiText in absolute coordinades:
var gui : GUIText;
function Awake() {
var obj = new GameObject("GuiText"+gameObject.name);
gui = obj.AddComponent("GUIText");
}
function Update() {
var pos = Camera.main.WorldToScreenPoint(transform.position);
gui.pixelOffset = pos;
}
You should not child GUIText or GUITexture to any 3D world object, due to the reason you’ve mentioned in your question - these elements use viewport coordinates in the position property. If you want a label to follow a 3D object, you must set its position each frame in Update. Usually the GUIText is a prefab and have a reference to the target object, like this:
var target: Transform; // drag the 3D object here
var offset: float = 1.5; // label offset in world space
function Update(){
var pos = target.position; // get the object position...
pos.y += offset; // calculate the position above the object...
// and set the GUIText position
transform.position = Camera.main.WorldToViewportPoint(pos);
}
On the other hand, if you want the GUIText to be part of the object prefab, reverse the logic: place a reference to the GUIText in some object script:
var label: GUIText; // drag the GUIText here from the Hierarchy view
var offset: float = 1.5; // label offset in world space
function Update(){
var pos = transform.position; // get the object position...
pos.y += offset; // calculate a position above the object...
// and set the GUIText position
label.position = Camera.main.WorldToViewportPoint(pos);
}
label.position can't compiled
– boboyon