我试图动态创建文本,所以我想在代码中创建文本。我试着这样做:
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";
}
上面的代码创建了文本对象,但没有显示它。
所有UI元素必须在Canvas GameObject中才能可见。所以你能做的就是在编辑模式下添加Canvas GameObject。或者在运行时:
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";
}