#What's the best way to create a canvas and add text to it in script
1 messages · Page 1 of 1 (latest)
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
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