Home > database >  How do I create a UI element from code that appears in Unity?
How do I create a UI element from code that appears in Unity?

Time:10-23

I'm trying to create text dynamically so I would like to create text in code. I tried doing it like this:

private void DrawIndexNumber()
{
    Text txt = new GameObject().AddComponent<Text>();
    txt.name = "Ind";
    txt.transform.position = _posOfOrigin;
    txt.material = materialNum;
    txt.font = Font.CreateDynamicFontFromOSFont("arial", 16);
        
    txt.text = "TEST";
}

The above code creates the text object but does not display it.

CodePudding user response:

All UI elements must be inside a Canvas GameObject to be visible. So what you can do is add the Canvas GameObject in edit mode. Or alternatively in runtime:

private void DrawIndexNumber()
{
    Canvas canvas = new GameObject().AddComponent<Canvas>();
    Text txt = new GameObject().AddComponent<Text>();
    txt.name = "Ind";
    txt.transform.position = _posOfOrigin;
    txt.transform.parent = canvas.transform;
    txt.material = materialNum;
    txt.font = Font.CreateDynamicFontFromOSFont("arial", 16);
    
    txt.text = "TEST";
}
  • Related