How to simulate a key press on button click - Unity

我与影子孤独终老i 提交于 2021-01-27 05:01:37

问题


I'm very new to scripting in Unity, I'm trying to create a button, and once clicked it needs to simulate the 'F' Key being pressed (To pick up an item)

Here is the current code I have, I've looked all over unity forums before writing this but couldn't find anything that worked.

Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
public class button : MonoBehaviour {

    public void ButtonToClick(int clickToButton)
    {
        SendKeys.Send("F");
    }
} 

回答1:


I believe simulating the key press is not the right way to do it.

Instead, you should call the PickUp function when the button is clicked the same way Pickup is called when the F key is pressed.

// Drag & Drop the object holding the script to the `OnClick` listener of your button
// Then, simply select the `Pickup` function
public void Pickup()
{
    // code ....
}

private void Update()
{
    if( Input.GetKeyDown( KeyCode.F ) )
        Pickup() ;
}



回答2:


From this question:

  1. Download zip file on http://inputsimulator.codeplex.com

  2. Unzip that to Assets directory with Your script (C#) in Unity project

  3. Reload MonoDevelop (if is opened)

  4. In script on top write: using WindowsInput;

  5. In your class you can use this, for example:

    InputSimulator.SimulateKeyPress (VirtualKeyCode.RIGHT); //simulate right arrow press

Edit:

You can install it without the above link using Nuget:

Install-Package InputSimulator

Check it's repository on github.



来源:https://stackoverflow.com/questions/48930193/how-to-simulate-a-key-press-on-button-click-unity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!