Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Cycle through array of letters

Discussion in 'Scripting' started by Deivydas4, Jan 20, 2023.

  1. Deivydas4

    Deivydas4

    Joined:
    Oct 28, 2021
    Posts:
    16
    Hello I'm doing a padlock, where player need to press buttons and select correct letter.


    Trying to do it with 'for' loop, but something doesn't quite gets for me. This is my code:

    Code (CSharp):
    1.     public char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
    2.     [SerializeField] private Text _letter01;
    3.  
    4.     public void UpArrow()
    5.     {
    6.         for (int i = 0; i < alpha.Length; i++)
    7.         {
    8.             _letter01.text = alpha[i].ToString();
    9.         }
    10.     }
    Thanks!
     
  2. SF_FrankvHoof

    SF_FrankvHoof

    Joined:
    Apr 1, 2022
    Posts:
    780
    Well currently you're looping through ALL letters, and setting them to the text.
    So you'll always end up with "Z", since that's the last letter.
    You should hold the index of the current letter.
    Then in UpArrow(), add 1 to that index, and set the Text to the new letter.


    Code (CSharp):
    1.     public char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
    2.     [SerializeField] private Text _letter01;
    3.  
    4.     private int currIndex = 0;
    5.     public void UpArrow()
    6.     {
    7.         currIndex++;
    8.         if (currIndex >= alpha.Length)
    9.             currIndex = 0; // Loop around
    10.         // Set Text to new Letter
    11.         _letter01.text = alpha[currIndex].ToString();
    12.     }
     
    SeerSucker69 and Bunny83 like this.
  3. Deivydas4

    Deivydas4

    Joined:
    Oct 28, 2021
    Posts:
    16
    Thank you!
     
  4. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    435
    After one picture, I can see that it will be an interesting game. Keep it up!
     
    Colonel_Campbell likes this.