Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
    }
like image 640
gn12345 Avatar asked Feb 12 '26 21:02

gn12345


1 Answers

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?

like image 53
Martín Isla Avatar answered Feb 15 '26 11:02

Martín Isla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!