Send a key press

Hi,

For a project i’m doing,i would like my program to send a Pressed Key.

I need this to try for instance to randomly press up/down/left/right on a snake game running of top of it.

(i think i should move to something else than Unity for what i’m trying to do but that’s the only thing i know :s)

So, is there a way to have every second something like “PressKey.Up” ?

Thanks !

Shakawah

What do you mean by “send”? Are you talking about displaying a UI Text to the player? If that is the case you have a GameObject with a Text component attached, and you have a control script which determines if it is being displayed or not. In its simplest form, you can display or hide the text by simply enabling/disabling either the GameObject or the Text component, but you can choose other methods like sliding if off the screen or fading it in and out.

Hi,

Thanks for your quick answer !

That’s not what i’m trying to do, i’m sorry i did not explained it well.

I want to simulate a key being pressed.
Every second i want my program to randomly (at the beginning) “press” up, down, left or right, to make a snake move (in another window).

So it would be a program that run in background.

Thanks :slight_smile:

You would need to generate a random number out of a list of 4 corresponding to a direction of the snake (1 up, 2 down, 3 left, 4 right for example).

Random.Range(0f, 4f)

I don’t think you need to simulate a key down, just have a seperate bit of code to generate these numbers and apply it to the part of the code that receives the key presses.

You seem to have the wrong idea. There isn’t a reason to simulate a key press. Look at it a different way.

When you push a key, some code runs. (current implementation)

Now, remove the key press and you just have code that doesn’t run, as it can’t be triggered.

So you want a way to trigger the code, but not based upon any user input. So, you have a timer that executes the code.

You want it to repeat, so you put it in a coroutine or use Update with a timer. Then you want it to have a random element of 4, so you have it generate a random number to change up a value of the code when it does run. (In this case, what direction the snake goes)

Also might need to be cautious of a game running in the background.

As far as I’m aware you cannot simulate real input directly, outside of OS specific calls.

Instead what you do is separate the code in your game which processes inputs from the code which acts on those inputs. Then you write a script which calls the same code in your game which acts on inputs just like the code calling it which is processing the inputs.

Oversimplified example:

public enum MoveDirection { None, Up, Down, Left, Right };
public bool EnableRandomMovement;  //Set to true to disable player controls and enable random movement
//Set to false to give control over to the player without random movement

void Update()
{
    if (EnableRandomMovement)
    {
        doRandomMovement();
    }
    else
    {
        processInput();
    }
}

//Process input from the player's keyboard to move the character
private void processInput()
{
    //Add code here which checks for keypresses by the player and then makes a call to MoveCharacter
}

//Moves the character in the supplied direction
//Ignore movement when supplied MoveDirection.None
public void MoveCharacter(MoveDirection moveDirection)
{
    //Have code here which moves the character based on the supplied moveDirection
}

//Generates a random number from 0 to 4, and converts that to a MoveDirection, then sends that to MoveCharacter
private void doRandomMovement()
{
    MoveDirection randomDirection = (MoveDirection)Random.Range(0, 5);
    MoveCharacter(randomDirection);
}

So above you would have all the Input.GetKey calls, or whatever you use to capture input, inside the processInput method. Based on that input you would pass a MoveDirection to MoveCharacter. But if you set EnableRandomMovement to true in the inspector, that will prevent processInput from getting called. Instead it will call doRandomMovement which picks a random direction (or None) and calls MoveCharacter just like you would from processInput.

Thanks again for the answers.

The snake isn’t a snake i did myself (and i would like to try other stuff on other games).

I would like to be able to run my program and then launch and existing game on which my simulated pressed button will have an effect.

The problem is “how to simulate a key being pressed to my computer”

(sorry if my english is not accurate :3)

Thanks

Well you’re probably looking for SendKeys.Send then. I have no idea if it is available within Unity, nor what OS’s it supports. You’ll also have to keep the game you’re trying control as the active application. If you click over to a web browser then the keys will be sent to the web browser instead for example.
https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys.send?view=netframework-4.8#System_Windows_Forms_SendKeys_Send_System_String_

This is really out of the scope of a Unity forum though, as it has nothing to do with game development. Sounds like you’re trying to write automation for playing someone else’s game. There’s plenty of premade automation tools out there which are probably better suited for what you’re trying to do.

1 Like

As far as I see it you have two ways to go about it, I often pondered on how one would do such a thing.

the first and most “naive” - make your functions like so

bool spaceKey, blahKey etcKey;

void Update(){

    if(Input.GetKey(KeyCode.Space) ||spaceKey){
        //do stuff
        spaceKey = false;
    }
}

this will turn into a great italian dish very fast if you need to account for stuff like the continuous GetKey or the Up variant.

the second option is to have some sort of master class that will handle all the input, and by that I mean that it will read what the Unity input system sends, have the ability to trigger stuff like we wished, and you just read your input from that.
I’m yet to attempt this challenge in the Unity editor so I’m not gonna start on the forum, but the idea is quite ‘simple’…

edit: oh god I don’t believe I didn’t think of going for the OS… this could be so simple.

1 Like

Ok joe-censored thanks for you answers. It’s true that this isn’t really a “game” but it still is scripting.
I think i should go try and learn to do this somewhere else than on unity but that’s the only thing i know for now ^^
I hoped that “SendKeys.Send” could work in Unity but i didn’t managed to do so :confused:

SparrowsNest, i’m sorry i didn’t really got what you were saying :open_mouth:

Most obvious languages - Python or C++ can be made to do this, you can make a standalone executable without the extra faff of Unity.

It would be like doing it in Maxscript or MEL - Unity isn’t suited to this type of thing!

1 Like

Ok, thanks, i’ll try to use something else than Unity then ^^
It was my “easy” option so I had to try :wink:

If you want to drive a windows application externally, simulating user input, the easiest choices would AutoHotKey or AutoIt. Both are free, well supported and documented.

Dear sir or madam
I need to build an on screen keyboard using unity
the link below present my idea

However, i need using unity C#
thank you?
Nima