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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Help with looping

Discussion in 'Getting Started' started by nameisinprocess, Jan 14, 2023.

  1. nameisinprocess

    nameisinprocess

    Joined:
    Jan 4, 2023
    Posts:
    6
    I learned the basics of C# over this last week, and I'm trying to make a numbers game to test some stuff out. I'm not getting any errors, but I don't know how to loop the if statement without crashing Unity.
    And I can't change the first method to "FixedUpdate()" because when I press "a" it prints it out around 5 times, and I need it to only print once.
    (I'm going to change the if statement later, right now it's set to "a" for testing purposes.)

    Have at thee:
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using UnityEngine;
    4. using System.Threading.Tasks;
    5.  
    6. namespace numbersGame
    7. {
    8. public class aSimpleNumbersGame : MonoBehaviour
    9.     {
    10.     void Start()
    11.             {
    12.                 if (Input.GetKey("a"))
    13.                 {
    14.                   AddNumber("a");
    15.                 }
    16.             }
    17.    
    18.     public string AddNumber(string key)
    19.     {
    20.      string message = "";
    21.      message = message + key;
    22.      print(message);
    23.      return message;
    24.     }
    25.     }
     
  2. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    437
    1. The Start method is executed only once at the beginning and the program does not return to it. In short, it is not used to take Input. Putting the Input function there doesn't make sense.
    2. The Update or FixedUpdate method is repeated while the program is running.
    3. To get exactly one keystroke, use GetKeyDown, as long as you hold it down, the operation will be performed only once (e.g. keyboard shortcut).
    4. The GetKey operation is run repeatedly as long as you hold the key (e.g. to move the character). That's why you get several additions to the number.
    In short, move Input to Update or FixedUpdate. And then change GetKey to GetKeyDown and everything should work.
     
    nameisinprocess likes this.
  3. nameisinprocess

    nameisinprocess

    Joined:
    Jan 4, 2023
    Posts:
    6
    That worked, thanks.