Unity 4.6+通过脚本创建文本

3

我正在尝试动态创建文本以根据玩家数量更改UI。但是,就目前的编码而言,对象已经创建,一切似乎都可以工作,除了文本在屏幕或场景视图中不可见。对象存在,只是文本不存在。有人能看出问题或知道如何解决吗?

顺便说一下,我正在使用C#。

public class UserInterface : MonoBehaviour {


public Canvas UI;
public GameObject DamageCounter;
public Color[] colors = new Color[4];

private static List<GameObject> players; 
Text uiText;
RectTransform uiPos;

// Use this for initialization
void Start () {

    players = PlayerManager.getPlayers ();
    float screenHalf = Screen.width / 2;
    float screenDiv = Screen.width / players.Count;
    Debug.Log ("ScreenDiv = " + screenDiv);


    for (int i = 1; i < players.Count + 1; i++) 
    {

        GameObject playerText = new GameObject("Text");
        playerText.layer = 5;
        uiPos = playerText.AddComponent<RectTransform>();
        uiText = playerText.AddComponent<Text>();
        playerText.transform.SetParent(UI.transform, false);
        uiPos.sizeDelta.Set(Screen.width, Screen.height);
        uiPos.anchoredPosition3D = new Vector3(0, 0, 0);
        uiPos.anchoredPosition = new Vector2(10, 10);
        uiPos.localScale = new Vector3(1.0f, 1.0f, 1.0f);
        uiPos.localPosition.Set(0, 0, 0);
        uiText.supportRichText = true;
        uiText.fontSize = 150;
        uiText.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
        uiText.alignment = TextAnchor.MiddleCenter;
        uiText.horizontalOverflow = HorizontalWrapMode.Overflow;
        uiText.verticalOverflow = VerticalWrapMode.Overflow;
        uiText.color = colors[i - 1];
        uiText.text = "WORK";
        Debug.Log ("HERE:" + (i * screenDiv - screenHalf));
    }
1个回答

2

你能确认文本是否在编辑器中的文本组件中显示吗?一旦点击播放,"WORK"应该会出现在那里。另外,控制台中是否有任何错误?


是的,在检查器中文本显示正确,控制台中也没有错误。 - gn12345
奇怪。您是否将“颜色”数组中的颜色设置为 alpha 为1f? - Martín Isla
哦,太感谢了。我知道这一定是个简单的问题,因为我没看出来有什么错误。非常感谢你,我已经撞了几个小时的墙(尴尬的是,现在看来问题如此简单)。 - gn12345
这种事情每个人都会遇到!哈哈,祝你的游戏好运! - Martín Isla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接