简体   繁体   中英

Unity 4.6+ Creating Text through a Script

I am trying to create text dynamically so that depending on the number of players, the UI changes. However as I've coded it at the moment, the objects are created and everything seems to work apart from the text is not visible on the screen or in scene view. The object is there, just not the text. Can anyone see the issue or know how to resolve this?

I'm using C# btw.

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));
    }

Can you check if the text is shown in the text component within the editor? As soon as you hit play, "WORK" should appear there. Also, is there any error in the console?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM