1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity(C#)】キーボードの連続入力を禁止する

Last updated at Posted at 2019-10-07

入力にインターバルを設ける

連続を禁止する、それすなわち入力にインターバルを設けるってことです。
もっとかみ砕いて言うと、
n秒間隔でしか入力ができないオレオレカスタムインプットを作ろうってことです。

コード

前回作った同時入力禁止のためのクラスに加筆しました。
かっこつけて見様見真似で<summary>を書いてます。間違ってたら陰で馬鹿にした後にご指摘お願いします。

CustomInput.cs
using UnityEngine;

namespace CustomInputKey
{
    /// <summary>
    /// Custom InputKey
    /// </summary>
    public static class CustomInput
    {
        static bool isCheck_Input;
        static bool preventContinuityInput;

        static float buttonDownTime;
        static float timer;

        /// <summary>
        /// Simultaneous input prohibited
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool SingleInputKeyDown(KeyCode key)
        {
            if (Input.anyKeyDown == false) isCheck_Input = false;

            if (isCheck_Input == false)
            {
                if (Input.GetKeyDown(key))
                {
                    isCheck_Input = true;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Continuity input prohibited
        /// </summary>
        /// <param name="key"></param>
        /// <param name="intervalSeconds"></param>
        /// <returns></returns>
        public static bool Interval_InputKeydown(KeyCode key,float intervalSeconds)
        {
            timer = Time.time;

            if (Input.GetKeyDown(key) && timer - buttonDownTime >= intervalSeconds)
            {
                if (preventContinuityInput==false)
                {
                    preventContinuityInput = true;
                    buttonDownTime = Time.time;
                    return true;
                }
                else if(preventContinuityInput)
                {
                    preventContinuityInput = false;
                    buttonDownTime = Time.time;
                    return true;
                }
            }

            return false;
        }
    }
}

  
呼び出すときは
namespaceにusing CustomInputKey;を書いて

インターバル3秒に設定して呼び出し
    if(CustomInput.Interval_InputKeydown(KeyCode.Space,3))
    {
        print("3秒待つと押せるよ");
    }

でいけます。

次回unity1week 10/14開催

次のunity1weekで活躍させて、操作性の向上につなげようと思います。

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?