Packages: Unity UI: CanvasScaler
Important setting: UI Scale mode
[SerializeField] TextMeshProUGUI textComponent; ... public void setScore(int newScore) { textComponent.text = $"Score: {newScore}"; }
TextMeshProUGUI
using TMPro;
UIManager
instance
UIManager.instance.UpdateScore()
using TMPro; public class UIManager : MonoBehaviour { public static UIManager instance; [SerializeField] TextMeshProUGUI scoreText; public int score = 0; void Start() { if (instance != null) Destroy(gameObject); else instance = this; } public void UpdateScore(int scoreChange) { score += scoreChange; scoreText.text = score.ToString(); } }
Packages: Unity UI: Interaction components
Button
Toggle
Slider
Scrollbar
Dropdown
Input Field
...
[SerializeField] Button _button; ... if (Input.ButtonDown("Fire1")) _button.onClick.Invoke();
using EventSystem ... EventSystem.current.SetSelectedGameObject(myButton);
RectTransform.position
RectTransform.localPosition
RectTransform.anchoredPosition
hpBarRT = GetComponent<RectTransform>(); ... public void AddHP(float newHP) { hp += newHP; hp = Mathf.Clamp(hp, 0, 100); hpBarRT.sizeDelta = new Vector2(width * hp / 100, hpBarRT.rect.height); }
[SerializeField] TextMeshProUGUI textComponent; [SerializeField] string[] lines = [], [SerializeField] float textSpeed int index; IEnumerator coTypeLine; void Start() { coTypeLine = TypeLine(); textComponent.text = ""; StartDialogue(); }
void StartDialogue() { index = 0; StartCoroutine(coTypeLine); } IEnumerator TypeLine() { foreach (char c in lines[index].ToCharArray()) { textComponent.text += c; yield return new WaitForSeconds(textSpeed); } }
void Update() { if (Input.GetButtonDown("Fire1") && (textComponent.text == lines[index])) { NextLine(); } if (Input.GetButtonDown("Fire2") && (textComponent.text != lines[index])) { StopCoroutine(coTypeLine); textComponent.text = lines[index]; } } void NextLine() { if (index < lines.length - 1) { index++; textComponent.text = ""; StartCoroutine(coTypeLine); } }
Continue the Exercise 3 from Collision. Create a counter for the collected items that sits on the top left corner of the screen.
See how UI scaling changes when you change the CanvasScaler component settings!
Create a UI with three buttons.
Change the color of a GameObject in your scene when the button has been pressed!
Try out setting RectTransform anchor points and see how the UI changes when you change the game resolution in the Game view.
if (GUI.Button(new Rect(100, 30, 150, 30), "Do a thing!")) { // When button is pressed, do a thing here }
value = GUI.TextField(new Rect(300, 30, 200, 20), value, 25);