Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Simulate Keypress

Discussion in 'Scripting' started by jorn818, May 25, 2016.

  1. jorn818

    jorn818

    Joined:
    May 12, 2013
    Posts:
    97
    So I know this was possible in 4.6 of Unity, now the code changed allot in Unity 5
    and im not the best coder now im wondering if it is still possible to simulate a keypress when I click on a 2d sprite with a 2d collider (box).

    so it would go like this

    1. click on sprite (with 2d collider)

    2. simulate the key ''i''

    not sure if this is hard or easy


    any help from a documentation till a complete script would be very appreciated!
     
  2. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    I don't think you want to be simulating keys by invoking the Events for key presses. Instead call the method that Key would have invoke should it have been pressed.

    Without any context this is what I could think of. Not sure what your trying to achieve.

    Code (CSharp):
    1. // If the 'I' key was pressed.
    2. if(Input.GetKeyDown(KeyCode.I)) {
    3.     SomeMethod();
    4. }
    5.  
    6. // If your sprite was pressed.
    7. void OnMouseDown() {
    8.     SomeMethod();
    9. }
     
    Kiwasi likes this.
  3. jorn818

    jorn818

    Joined:
    May 12, 2013
    Posts:
    97
    im trying to achieve the ability to press ''i'' without a keyboard, but by clicking on a sprite with my mouse ingame
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You can't mess with the Input class manually. So typically you need a layer of abstraction between Input and your code. That way you can fake the input when the conditions are right.

    Basically what @Polymorphik said.
     
    Polymorphik likes this.
  5. pvzkiller

    pvzkiller

    Joined:
    Oct 3, 2012
    Posts:
    7
    >>>May be useful with the ZFBrowser asset from the Unity Asset Store in order to automatically feed some values into the webpage!