#What's the best way to create a canvas and add text to it in script

1 messages · Page 1 of 1 (latest)

jaunty cargo
#

I've been developing a simple game as a fun project and i want to add a player UI with script. Would you be so kind and tell me if this is a good way to handle it? Sorry if its messy kinda new to this.

#
    public PlayerUI()
    {
        canvasObject = new GameObject("PlayerUI");
        playerUI = canvasObject.AddComponent<Canvas>();
        canvasScaler = canvasObject.AddComponent<CanvasScaler>();

        playerHealth = new GameObject("PlayerHealth");
        playerAmmo = new GameObject("PlayerAmmo");

        InitialiseUI();
    }

    private RectTransform SetupRectTransform(GameObject obj, Vector2 anchor, float width)
    {
        RectTransform rectTransform = obj.AddComponent<RectTransform>();
        rectTransform.anchorMin = anchor;
        rectTransform.anchorMax = anchor;
        rectTransform.pivot = anchor;
        rectTransform.sizeDelta = new Vector2(width, rectTransform.sizeDelta.y);

        return rectTransform;
    }

    private Text SetupText(GameObject obj, string content, TextAnchor anchor, byte fontSize, Font font)
    {
        Text text = obj.AddComponent<Text>();
        text.text = content;
        text.alignment = anchor;
        text.fontSize = fontSize;
        text.font = font;

        return text;
    }

    private void InitialiseUI()
    {
        canvasObject.transform.SetParent(Player.PlayerInstance.transform);
        playerAmmo.transform.SetParent(canvasObject.transform);
        playerHealth.transform.SetParent(canvasObject.transform);

        playerUI.renderMode = RenderMode.ScreenSpaceOverlay;
        
        SetupRectTransform(playerHealth, new Vector2(0, 0), 400f);
        SetupRectTransform(playerAmmo, new Vector2(1, 0), 400f);

        SetupText(playerAmmo, "MagezineA / Ammo", TextAnchor.LowerRight, 50, FontManager.GetFontFromDictionary("MainFont"));
        SetupText(playerHealth, "100", TextAnchor.LowerLeft, 50, FontManager.GetFontFromDictionary("MainFont"));
        
        canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
        canvasScaler.referenceResolution = new Vector2(1920, 1080);
    }
#

Couldn't really fit the whole thing in

past harness
#

Usually you create it as a UI prefab, and only make very select changes (i.e. content to text boxes and event listening). You can do it via script but it's a lot less flexible

jaunty cargo
#

Oh that would make a lot of sense

#

Basically could delete this whole code

#

And if i understand it correctly i could just set the UI prefab to an instance of the player class

#

And make alterations to the text boxes like setting the content to player hp etc..