0

I am trying to make a small game, where you have to press a specific key in less than a second, or you lose. My idea for it is to generate random letter, start a timer, check if player has done it in time if yes, then repeat, if no then lose the game.

Now to the problem, I have a code for random letter, but when I try to get input for it, Unity says: ArgumentException: Input Key named: K is unknown

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TextCounter : MonoBehaviour
{
    

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        char Random_Letter = (char)('A' + Random.Range(0, 26)); // Choose random key

        if (Input.GetKeyDown("" + Random_Letter))
        {
            // Score a point
        }

        ActiveOnTimer();  // Wait a second


    }

    private IEnumerator ActiveOnTimer()
    {
        while (true)
        {
            yield return new WaitForSeconds(1f);
        }
    }
}

Here is the code, but I belive the real problem is in char Random_Letter = (char)('A' + Random.Range(0, 26)); // Choose random key if (Input.GetKeyDown("" + Random_Letter))

Hope someone can help me

frankhermes
  • 4,720
  • 1
  • 22
  • 39

1 Answers1

0

Currently your timer does absolutely nothing.

A Coroutine doesn't delay the code outside of it. Also you can't just call a Coroutine like a normal method you would need to start it using StartCoroutine

Also afaik the characters for the string version have to be lower case! In general I would rather stick to KeyCode anyway though.

What you rather want to do is

public class TextCounter : MonoBehaviour
{
    public int points;

    public float delay = 1f;

    // Yes, if you make Start return IEnumerator it is automatically started as a Coroutine
    IEnumerator Start()
    {
        while (true)
        {
            // In general instead of the string versions I would rather stick to KeyCode
            KeyCode Random_Letter = (KeyCode)(((int)KeyCode.A) + Random.Range(0,26));
            // otherwise probably
            //string Random_Letter = "" + (char)('a' + Random.Range(0,26));

            Debug.Log($"You have {delay} seconds from now to press {Random_Letter}");

            // This loop will iterate for "delay" seconds
            for(var timePassed = 0f; timePassed < delay; timePassed += Time.deltaTime)
            {
                if (Input.GetKeyDown(Random_Letter))
                {
                    points++;
                    Debug.Log($"Yeay, Now you have {points} points!");

                    // You probably want to break here in order to immediately go to the next random key
                    // otherwise the user could just spam the key to get points
                    break;
                }

                yield return null;
            }       
        }
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115