0
\$\begingroup\$

I want to print the sum of two numbers, but only when I press the enter key. Pressing any other key should give me the message "Invalid Key". Now the output I am getting is an endless loop of "Invalid key", until I press another button.

This is my log, with the "Invalid Key" message being repeated.

How do I only produce the output when I press a key?

using UnityEngine;
using System.Collections;

public class LearningScript : MonoBehaviour {

    public int number1 = 5;
    public int number2 = 10;
    public bool condition;
    public int answers;

    void Update()
    {  
        if (Input.GetKey (KeyCode.Return))
            condition = true;
        else
            condition = false;

        if (condition)
            Debug.Log (answers);
        else
            Debug.Log ("INVALID KEY");
    }

    void Start()
    {
        answers = addTwonumbers (number1, number2);         
    }

    int addTwonumbers(int num1,int num2)
    {
        int result = num1 + num2;
        return result;
    }           
}
\$\endgroup\$
4
\$\begingroup\$

Modify your Update to look like below:

void Update ()
{
    if (Input.GetKeyDown(KeyCode.Return))
    {
        condition = true;
        Debug.Log(answers);
    }
    else if (Input.anyKeyDown)
    {
        condition = false;
        Debug.Log("INVALID KEY");
    }
}

Printing the "Invalid Key" message without a condition is causing the message to print in every frame, whenever you are not pressing the enter key.

Also use GetKeyDown to avoid multiple calls from a single press that spans multiple frames.

\$\endgroup\$
2
  • \$\begingroup\$ Yeah, you're right. That's what I get for writing out an answer before waking up properly. ;) \$\endgroup\$ Sep 2 '16 at 8:24
  • \$\begingroup\$ Been there. ;) ... \$\endgroup\$ Sep 2 '16 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.