Is it possible to simulate a keypress/input in code?

Say i had an input named ‘fire’ mapped to a key ‘z’. Is there any way to simulate either a button press or input value (within a ngui on screen button) in code rather than creating isolated functions for the fire action?

This is solution:

  1. Download zip file on:
  2. Unzip that to Assets directory with Your script (C#) in Unity project
  3. Reload MonoDevelop (if is openend)
  4. In script on top write: using WindowsInput;
  5. and … in class You can use this for example: InputSimulator.SimulateKeyPress (VirtualKeyCode.RIGHT); //simulate right arrow press
  6. Enjoy :slight_smile:

I would suggest this answer

The post mentioned by petrnita worked perfectly for me on Windows in Unity 2019. I see a few people mentioned that they got missing namespace errors trying to use the solution he linked; to fix this go into the “inputsimulator\sourceCode\inputsimulator” directory of the download, then delete the “WindowsInput.SampleClient.Wpf” and “WindowsInput.Tests” folders.

The API is also used differently since his answer was shared. Use the API as shown below:

using UnityEngine;
// Include the WindowsInput namespace
using WindowsInput;

public class InputTest : MonoBehaviour

    public void TestKeyInput()
        // Build an input simulator instance
        InputSimulator inputSimulator = new InputSimulator();
        // Then call the keyboard key down method, pass in the enum virtual key code you want to press


The best option is to just add a function for firing but if you don’t want to do that you can try:

JavaScript: javascript - Is it possible to simulate key press events programmatically? - Stack Overflow

C# :

These solution may or may not working in unity but it is what I found on the internet

I strongly suggest making a function as you may find that you want to fire in many different ways and functions just simplify your code so much.

Create Empty Object and disable it.
Word the if statement with an || option.

Than you can trigger the key if statement just by activating the “KeyObject” from any script.

public GameObject keyObject;

if (Input.GetButtonUp (Key) || keyObject.activeSelf == true) {

keyObject.SetActive (false);


Now from a different script …

public GameObject keyObject;

keyObject.SetActive (true);

Try this one. It worked for me.

Keyboard keyboard = InputSystem.GetDevice<Keyboard>();
Key[] pressedKeys = new Key[] { Key.Z };
KeyboardState keyboardState = new KeyboardState(pressedKeys);
InputSystem.QueueStateEvent(keyboard, keyboardState);

Sorry I’m late.