Advertisement
BenTibnam

Generic Selection Menu TMP in Unity

Jan 5th, 2023
832
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using TMPro;
  4. using Unity.VisualScripting;
  5. using UnityEngine;
  6.  
  7. public class MainMenuNavigation : MonoBehaviour
  8. {
  9.     [SerializeField] private TextMeshProUGUI[] menuText;
  10.  
  11.     private int totalMenuOptions;
  12.     private int currentIndex = 0;
  13.     private KeyCode selectionUp = KeyCode.UpArrow;
  14.     private KeyCode selectionDown = KeyCode.DownArrow;
  15.  
  16.     private void Start()
  17.     {
  18.         totalMenuOptions = menuText.Length;
  19.         UpdateSelectedMenuItem(0, 0);
  20.     }
  21.  
  22.     private void UpdateSelectedMenuItem(int pastSelected, int newSelected)
  23.     {
  24.         TextMeshProUGUI pastSelectedText = menuText[pastSelected];
  25.         TextMeshProUGUI currentSelectedText = menuText[newSelected];
  26.  
  27.         if (pastSelectedText.text[0] == '>')
  28.         {
  29.             pastSelectedText.text = pastSelectedText.text.Substring(2);
  30.         }
  31.  
  32.         currentSelectedText.text = "> " + currentSelectedText.text;
  33.     }
  34.  
  35.     private void Update()
  36.     {
  37.         if (Input.anyKey)
  38.         {
  39.             int previousSelection = currentIndex;
  40.  
  41.             if (Input.GetKeyDown(selectionUp))
  42.             {
  43.                 currentIndex = (currentIndex - 1 < 0) ? totalMenuOptions - 1 :  currentIndex - 1;
  44.             }
  45.  
  46.             if (Input.GetKeyDown(selectionDown))
  47.             {
  48.                 currentIndex = (currentIndex + 1 > totalMenuOptions - 1) ? 0 : currentIndex + 1;
  49.             }
  50.  
  51.             UpdateSelectedMenuItem(previousSelection, currentIndex);
  52.         }
  53.     }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement