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. Dismiss Notice

How to trigger a keyboard key press event without pressing the key from keyboard

Discussion in 'Scripting' started by Mystigan, Jan 17, 2015.

  1. Mystigan

    Mystigan

    Joined:
    Dec 6, 2014
    Posts:
    4
    I was wondering how you would do this in unity C# , I need to trigger enter key press . I know it is possible to do this in WPF(visual studio) C# but not in unity.
    Thanks in advance. :)
     
  2. TheSniperFan

    TheSniperFan

    Joined:
    Jul 18, 2013
    Posts:
    712
    I'm not sure whether there's an easier way, but you could always write your own input manager that allows you to do just this.

    Before going ahead and implementing one, I'd wait for some more replies though.
     
    Kiwasi likes this.
  3. Mystigan

    Mystigan

    Joined:
    Dec 6, 2014
    Posts:
    4
    Thanks but I thought there might be a simpler way I mean In visual C# i can do that using this code. So it should work in unity C# as well right in some modified form?

    Code (CSharp):
    1.  
    2. var key =Key.A;// Key to sendvar target =Keyboard.FocusedElement;// Target elementvar routedEvent =Keyboard.KeyDownEvent;// Event to send
    3.  
    4. target.RaiseEvent(newSystem.Windows.Input.KeyEventArgs(Keyboard.PrimaryDevice,System.Windows.PresentationSource.FromVisual((Visual)target),0, key){RoutedEvent= routedEvent });
     
  4. TheSniperFan

    TheSniperFan

    Joined:
    Jul 18, 2013
    Posts:
    712
    Unity isn't using .net, but mono. System.Windows.Input isn't available. Look for an alternative.
     
  5. cmcpasserby

    cmcpasserby

    Joined:
    Jul 18, 2014
    Posts:
    315
    Why would you ever need this, if you do your input code is too tightly coupled with your logic.
     
    Joe-Censored and Kiwasi like this.
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Unfortunately there is no easy answer for this. The two solutions suggested already are worth pursuing.

    I would suggest decoupling as being the better to implement straight off the bat.
     
  7. Amyr

    Amyr

    Joined:
    Sep 21, 2014
    Posts:
    5
    I want this for testing on Test Runner.
    I wander if there is a way to throw a key press event on the EventSystem or something.