- Home /
Position Text at gameObject position
I am having trouble moving my text anywhere except the default start position. I think it may be because I am not changing game position to GUI world position but I don't know how to change it correctly (I am very new to this).
It is a 2d game.
Here is my code
void OnTriggerEnter2D(Collider2D other) {
Text tempTextBox = Instantiate(addScoreText, other.transform.position, Quaternion.identity) as Text;
tempTextBox.transform.SetParent(renderCanvas.transform, false);
tempTextBox.text = updateScore.ToString();
}
addScoreText is a text prefab.
So the text shows but not at the right position.
Any ideas as to how to make this work?
Thanks
Answer by SamohtVII · Apr 08, 2018 at 07:55 AM
For reference to anyone else, this is how I did it...
public Camera Cam;
RectTransform CanvasRect;
public Canvas canvas;
Vector3 screenPos = cam.WorldToScreenPoint(other.transform.position);
Text tempTextBox = Instantiate(addScoreText, other.transform.position, Quaternion.identity) as Text;
Vector3 ViewportPosition=Cam.WorldToViewportPoint(other.transform.position);
Vector2 WorldObject_ScreenPosition=new Vector2(
((ViewportPosition.x*CanvasRect.sizeDelta.x)-5.0f),
((ViewportPosition.y*CanvasRect.sizeDelta.y)+16.0f));
tempTextBox.transform.SetParent(renderCanvas.transform, false);
tempTextBox.rectTransform.position = WorldObject_ScreenPosition;
tempTextBox.text = "+"+updateScore.ToString();
Answer by tormentoarmagedoom · Apr 07, 2018 at 08:59 AM
Good day.
I recoomend to instantiateas gameobject only with the parent, and then move it.
GameObject tempTextBox = Instantiate(addScoreText, other.transform.position) as GameObject;
tempTextBox.transform.localposition = (PositionYouwant refered to its parent)
tempTextBox. text = "What you want to say"
Bye! :D
Accept the answer if hellped :D
Hey I am using Unity 4.7 and for the sake of finishing this game I will stick with it for now. This throws some errors that may be associated with the version. Any help for 4.7? Thanks
Your answer

Follow this Question
Related Questions
how to scale and position guiText in android 1 Answer
UI text hidden at different resolutions. 1 Answer
Get position of specific letter in UI Text 4 Answers
Display text on Cloud sprites 1 Answer
Help making a damage number system 1 Answer