3D Text Size Relative To Screen?

Hello.

I recently added some 3D text to my scene to follow the top of the player. This was done so the Player’s name wouldn’t appear when he was behind a building.

I got that to successfully work, but the only problem I’m having now that I moved it into 3D space, is that the text doesn’t keep the same size relative to the screen size. The further you go away, the the harder it is to notice the player’s name. Anyone know how to keep the size consistent relative to the screen?

Thank you

  • Adam

You could set the scale of the textGameObject in according to the distance from the camera in this way:

using UnityEngine;

public class ScaleMeshText : MonoBehaviour {
	[Tooltip("Distance of the MeshObject with no calculateScale")]
	public float distance = 7.0f;
	Vector3 startScale;

	void Start () {
		startScale = transform.localScale;
	}
	
	void Update () {
		scale();
	}

	void scale()
	{
		float dist = Vector3.Distance(Camera.main.transform.position, transform.position);
		Vector3 newScale = startScale * (dist / distance);
		transform.localScale = newScale;
	} 
}

Use a GUIText object instead of 3D text. (For example.)

Obviously this is an old thread, but just thought I would help anybody else looking for an answer. The first thing you must do is pick a default font size and relative default distance, like so:

float defaultDistance = 4f;
float defaultSize = 40f;

Then use something like this to resize it:

float dist = Vector3.Distance(playerCamera.position, transform.position);
textMesh.fontSize = Mathf.RoundToInt(defaultSize * Mathf.Sqrt(dist / defaultDistance));

The square root is key here, because otherwise the text will scale disproportionately to the camera’s distance.

You could set the scale of the object according to the distance from the camera. You will have to adjust the values/settings but basically just use Vector3.Distance on the camera transform and the 3d text transform.

public class Example : MonoBehaviour {
    public Transform cameraTransform;
    void Example() {
        if (other) {
            float dist = Vector3.Distance(cameraTransform.position, transform.position);
            print("Distance to other: " + dist);
            Vector3 newScale = transform.localScale;
            // adjust local scale based on distance
            transform.localScale = newScale;
        }
    }
}

You can also combine this with http://wiki.unity3d.com/index.php?title=CameraFacingBillboard for other types not just 3d text.