- Home /
2D Draw text at sprite position with script only
I would like to know how i can draw text at the X and Y position of an sprite when i clicked on it. But i realy dont know how to draw text onto the location of the Sprite.
So how can i do that without adding a GUIText to the object. Also I`m using C#
Answer by SkyRamon · Feb 16, 2015 at 10:12 AM
After doing some research i finally figured out how to draw text on the object i was looking for.
because i encoutered problems with camera is not attach to object i tried using a camera variable, and that worked. also im using a vector3 variable so i can use that everywhere on my script. instead of drgging your object onto the script variable you could also use something called FindObject by Tag or name but im not sure how that works
public Transform Planet;
public Camera cameraobj;
public Vector3 screenPos;
to update and keep track of the objects location i used this code:
void Update () {
screenPos = cameraobj.WorldToScreenPoint(Planet.position);
print("target is " + screenPos.x + " pixels from the left");
}
and to view the text i used this code: im using screenPos.x-48 to set it exactly in the center of my object also i used MyStyle as GUIStyle to center my text at MiddleCenter then i calculated what the difference was between where the text is supposed to be and where is was now.
e.x : the object is 123px from the left but when i set it manualy in the center it is 103px from the left. so i need to grab the ScreenPos.X wich is equal to 123px and minus it with 20px to center is perfectly...
and i used some colors and sizes...
code:
void Update () {
screenPos = cameraobj.WorldToScreenPoint(Planet.position);
print("target is " + screenPos.x + " pixels from the left");
OnGui();
}
private void OnGUI() {
GUI.Label(new Rect(screenPos.x-48,screenPos.y-23, 100, 50), "<color=white><size=40>" + Ships + "</size></color>", MyStyle);
}
Your answer
Follow this Question
Related Questions
Recommended sprite drawing resolution 1 Answer
Mapping 2d texture onto another 2d texture 0 Answers
Display UI Text on a 2D Sprite 1 Answer
Basic: Text sub-component of sprite prefab not showing 0 Answers
Sprites not drawing, why? 0 Answers