Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by BloodyTeddy · Dec 04, 2018 at 04:33 PM · updatetimefunctionskeys

Trying to write a function that checks if 2 keys are pressed

So I'm trying to write a function that checks if 2 keys are pressed within 1 second if each other:

 bool IfTwoKeysPressed(string Key1, string Key2)
 {
     float FirstKeyPress = 20;
     float SecondKeyPress = 50;
     float TimePressedDelay = 1;
     bool KeysPressed = false;

     if (Input.GetKeyDown(Key1))
     {
         FirstKeyPress = Time.time;
     }
     if (Input.GetKeyDown(Key2))
     {
         SecondKeyPress = Time.time;
     }
     if (Mathf.Abs(SecondKeyPress - FirstKeyPress) <= TimePressedDelay)
     {
         FirstKeyPress = 20;
         SecondKeyPress = 50;
         KeysPressed = true;
     }
     Debug.Log(KeysPressed);
     return KeysPressed;
 }

Problem is when I call this function in Update(), checking the delay between the 2 presses doesn't work since the function happens within 1 frame and resets. Transferring the code into Update() works but in my game I'm going to have to check a lot of key combinations and would prefer not having to creating all the variables and writing this code every time.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by michi_b · Dec 04, 2018 at 05:11 PM

You have to store the last times the keys have been pressed manually. Then, each time a new key has been pressed, check if all the keys have been presses in your time frame (1 second). Let me give you a helper class that manages that:

 using System;
 using System.Collections.Generic;
 using UnityEngine;
 
 [Serializable]
 public class MultiKeyPressChecker
 {
     [Serializable]
     private class KeyData
     {
         [SerializeField, Tooltip("key that has to be pressed to trigger")] private KeyCode key = KeyCode.A;
 
         [SerializeField]private float lastPressTime = float.NegativeInfinity;
 
         public void Update()
         {
             if (Input.GetKeyDown(key))
             {
                 lastPressTime = Time.time;
             }
         }
 
         public bool GetWasPressed(float timeFrame)
         {
             return Time.time - timeFrame < lastPressTime;
         }
 
         public void ClearLastKeyPressTime()
         {
             lastPressTime = float.NegativeInfinity;
         }
     }
 
 
     [SerializeField, Tooltip("keys that have to be pressed in the timeframe to make the check trigger")]
     private List<KeyData> keys;
 
     [SerializeField, Tooltip("duration in which all specified keys have to be pressed")]
     private float timeFrame = 1f;
 
     public bool Check()
     {
         foreach (KeyData key in keys)
         {
             //update last press times of keys
             key.Update();
         }
 
         foreach (KeyData key in keys)
         {
             //if any of the keys was not pressed in the timeframe, return false
             if (!key.GetWasPressed(timeFrame))
             {
                 return false;
             }
         }
 
         //else clear last key presses and return true (all keys have been pressed in the timeframe)
         foreach (KeyData key in keys)
         {
             key.ClearLastKeyPressTime();
         }
         return true;
     }
 }

You can use this helper class like in this example script:

 using UnityEngine;
 
 public class MultiKeyPressExample : MonoBehaviour
 {
     [SerializeField] private MultiKeyPressChecker keyPressChecker;
 
     private void Update()
     {
         if (keyPressChecker.Check())
         {
             Debug.Log("all the specified keys have been pressed in the timeframe");
         }
     }
 }

Just assign the keys you are interested in and the allowed timeframe in the inspector and you are good to go.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image BloodyTeddy · Dec 19, 2018 at 02:44 PM 0
Share

Hey again So this worked great, but now I've run into the problem that you can just press all the buttons on the keyboard and as long as those buttons contained the required keys, the action happens. Any ideas on how to fix this?

avatar image
0

Answer by Vega4Life · Dec 04, 2018 at 05:27 PM

I created a double key press script. Thus, if other scripts need to use it, just add it and check for the keys you need. I also changed a few lines of code as well, as I don't think you need to keep time for each button press.


 using UnityEngine;
 
 // I wouldn't worry about time for each key.  You just need a global time from the last one clicked
 public class DoubleKeyPress : MonoBehaviour
 {
     bool key1Pressed;
     bool key2Pressed;
     float countDownSinceKeyPressed = 0;
     float TimePressedDelay = 1;
 
 
     public bool IfTwoKeysPressed(KeyCode key1, KeyCode key2)
     {
         countDownSinceKeyPressed -= Time.deltaTime;
         if (countDownSinceKeyPressed <= 0)
         {
             key1Pressed = false;
             key2Pressed = false;
         }
 
         if (Input.GetKeyDown(key1))
         {
             countDownSinceKeyPressed = TimePressedDelay;
             key1Pressed = true;
         }
 
         if (Input.GetKeyDown(key2))
         {
             countDownSinceKeyPressed = TimePressedDelay;
             key2Pressed = true;
         }
 
         if (key1Pressed && key2Pressed) countDownSinceKeyPressed = 0f;
 
         return key1Pressed && key2Pressed;
     }
 }



Here is a random script that adds it and uses it.


 using UnityEngine;
 
 public class UseDoubleKeyPress : MonoBehaviour
 {
     DoubleKeyPress keyPress;
 
 
     void Awake ()
     {
         keyPress = gameObject.AddComponent<DoubleKeyPress>();
     }
     
 
     void Update ()
     {
         if (keyPress.IfTwoKeysPressed(KeyCode.A, KeyCode.B))
         {
             Debug.LogError("Buttons Pressed");
         }
     }
 }


Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image michi_b · Dec 04, 2018 at 05:46 PM 0
Share

yep, for just two keys this works, have to add though that when you use a counter ins$$anonymous$$d of a stored time, you accumulate a floating point precision error, which should be negligible in this context though.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

99 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

when is pysics.raycast used, if it is called in Update() 1 Answer

Movement using Time.deltaTime not working on Fast mac 3 Answers

Slow update best practice 0 Answers

regenerating stats in update(); 1 Answer

My variable doesn't update real-time? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges