Get Off My Lawn
Get Off My Lawn

Reputation: 36341

Create GUI text above killed character

I am making a top down 2D game, and I am not sure how to place text above a character when then die.

I created a prefab with an empty game object which has a GUIText component attached to it. When my object dies I need to create the prefab object above it. When the object dies, the prefab is created in the correct spot, but the text is usually way off of the screen... Why is it doing that?

Here is the code:

void destroySelf(){
    Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
    GameObject obj = GameObject.Instantiate(pointsTxt, transform.position / 0.1f, Quaternion.identity) as GameObject;
    obj.GetComponent<GUIText>().text = "+" + killPoints.ToString();
    Destroy(transform.parent.gameObject);
}

Upvotes: 2

Views: 2716

Answers (2)

Kazuki Sakamoto
Kazuki Sakamoto

Reputation: 14009

You can also use TextMesh instead of GUIText like this http://answers.unity3d.com/questions/13625/procedurally-generate-a-textmesh.html

var textMesh = gameObject.AddComponent<TextMesh>();
textMesh.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
var meshRenderer = gameObject.GetComponent<MeshRenderer>();
meshRenderer.material = textMesh.font.material;
textMesh.fontSize = 16;
textMesh.alignment = TextAlignment.Center;
textMesh.anchor = TextAnchor.MiddleCenter;
textMesh.text = "Hello";

Upvotes: 0

Chris McFarland
Chris McFarland

Reputation: 6169

GUIText world positioning works in a 0..1 range. transform.position = Vector3(0,0,0) is the equivalent of bottom-left corner of the screen; transform.position = Vector3(1,1,0) is the top-right corner of the screen.

You've got the right idea using WorldToScreenPoint; now you just need to get the position values within the 0..1 range:

Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
pos.x = pos.x / Screen.width;
pos.y = pos.y / Screen.height;
GameObject obj = GameObject.Instantiate(pointsTxt, pos, Quaternion.identity) as GameObject;

Alternatively, you could leave the GUIText's position as Vector3.zero (default from Instantiate), and alter its pixelOffset values instead:

Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
GameObject obj = GameObject.Instantiate(pointsTxt) as GameObject;
GUIText text = obj.GetComponent<GUIText>();
text.pixelOffset.x = pos.x;
text.pixelOffset.y = pos.y;

Upvotes: 2

Related Questions