Home > front end >  Unity: Add a Text Using a TextMesh Via Script?
Unity: Add a Text Using a TextMesh Via Script?

Time:11-08

I just want to be able to see some text rendered in the world.

The only example code that I've found is this:

  GameObject Text = new GameObject();      
  TextMesh textMesh = Text.AddComponent<TextMesh>();
  textMesh.font = new Font();
  mat.SetColor("_Color", Color.black);
  mat.SetPass(0);       
  meshRenderer.material = mat;
  textMesh.text = "Hello World!";       

Where mat is defined by the code:

  Shader shader = Shader.Find("Hidden/Internal-Colored");
  mat = new Material(shader);
  mat.hideFlags = HideFlags.HideAndDontSave;     
  mat.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
  mat.SetInt("_ZWrite", 0);   
  mat.SetColor("_Color", Color.blue);
  mat.SetPass(0);       

This code is added to the Start of MonoBevaviour. And the script is tied to Game Main camera.

No text appears anywhere that I can see.

CodePudding user response:

Ah I think I might have something.

I am not sure though if this works for VR devices - I know that Unity e.g. doesn't render Screenspace overlay canvas on XR.

But back to the point: There is a legacy UI system which is usually not used anymore except for in editor Inspector scripting IMGUI

I think it might actually fit your very special need using GUILayout.Label you should be able to draw a flat label onto the screen even in VR.

With GUI.Label you have full control over the pixel coordinates and size.

public class YourTextDrawer : MonoBehaviour
{
    void OnGUI() 
    {
        var color = GUI.color;
        GUI.color = Color.green;
        var textPosition = new Rect(Screen.width / 2 - 150, Screen.height / 2 - 100, 300, 200);
        GUI.Label(textPosition, "Hello World!");
        GUI.color = color;
    }
}

Not tested, just scrabbling this down from memory right now


And actually thinking about it, this might even work for your image as well

CodePudding user response:

Just use TextMeshPro.

Right click to hierarchy -> 3D Object -> Text - TextMeshPro.

Then you will see a text appear in your scene. You can use that in 3D space.

  • Related