- Home /
check if 'B' key is being pressed while clicking in Editor window
Hi , i have a strange issue. i simply need to check if the B key and a left mouse click event happens at the same time.
this doesn't work
if (Event.current.type == EventType.MouseDown && Event.current.keyCode == KeyCode.B)
Debug.Log("you clicked while pressing B ");
but these work
if (Event.current.type == EventType.MouseDown )
Debug.Log("clicking");
if ( Event.current.keyCode == KeyCode.B )
Debug.Log("pressing B");
Why is the combined function not working ?
Answer by Eno-Khaon · May 07, 2018 at 09:18 AM
You will not see a Mouse and Keyboard Event occurring simultaneously. With this in mind, I would advise keeping tabs on any relevant keyboard input when possible. for example:
// C#
private bool bKeyHeld;
// ...
void OnGUI()
{
Event e = Event.current;
// If statements are left separate in case
// you intend to utilize more key/mouse buttons
if(e.type == EventType.KeyDown)
{
if(e.keyCode == KeyCode.B)
{
bKeyHeld = true;
}
}
else if(e.type == EventType.KeyUp)
{
if(e.keyCode == KeyCode.B)
{
bKeyHeld = false;
}
}
if(bKeyHeld)
{
if(e.type == EventType.MouseDown)
{
if(e.button == 0)
{
// Left Mouse Button down while holding B
}
}
}
}
A large number of events are spit out by Unity, so you could utilize Event.isKey or Event.isMouse as additional filters if desired.
Additionally, you may need to make a check for when Unity gains/loses focus to ensure the state of any held key is not out of sync if you switch to/away from the editor.
Answer by KittenSnipes · May 07, 2018 at 08:14 AM
@DMDev Try this:
if (Input.GetKey(KeyCode.Mouse0))
{
if (Input.GetKeyDown(KeyCode.B))
{
//Code here
}
}
Or you could use this but I think it has to be exactly the same time in the same frame which seems a bit hard so you could use some form of timer if it comes to it:
if (Input.GetKeyDown(KeyCode.Mouse0) && Input.GetKeyDown(KeyCode.B))
{
//Code here
}
So you are running this during edit time and not run time, correct?
Can you show exactly what you are trying to do with the script? This should work
@D$$anonymous$$Dev Try putting this in your script. It should be put above where your class starts:
Example:
[ExecuteInEdit$$anonymous$$ode]
public class Zombie: $$anonymous$$onoBehaviour
Answer by Timbaluke · May 07, 2018 at 08:32 AM
Check either the b-key or the mouse button with Input.GetKey instead of Input.GetKeyDown. Check for Input.GetKey before you check for Input.GetKeyDown. GetKey returns true as long as the key is pressed, GetKeyDown only returns true for one frame. If you use GetKeyDown both keys/buttons have to be pressed at the exact same time/frame (down to miliseconds).
if (Input.GetKey(KeyCode.B))
{
if (Input.GetKeyDown(KeyCode.Mouse0)
{
// code
}
}
this one also doesn't work in my editor window script