如何模拟按钮单击时的按键 - Unity



我对 Unity 中的脚本很陌生,我正在尝试创建一个按钮,单击它需要模拟按下的"F"键(拿起一个项目)

这是我当前的代码,在写这篇文章之前,我已经浏览了 Unity 论坛,但找不到任何有用的代码。

法典:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
public class button : MonoBehaviour {
public void ButtonToClick(int clickToButton)
{
SendKeys.Send("F");
}
} 

我相信模拟按键不是正确的方法。

相反,您应该在单击按钮时调用PickUp函数,其方式与按下F键时调用Pickup相同。

// 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() ;
}

从这个问题:

  1. 在 http://inputsimulator.codeplex.com 上下载zip文件

  2. Unity 项目中使用脚本 (C#) 将其解压缩到资产目录

  3. 重新加载单体开发(如果打开)

  4. 在顶部写入脚本中:使用WindowsInput;

  5. 在您的类中,您可以使用它,例如:

    InputSimulator.SimulateKeyPress (VirtualKeyCode.RIGHT);//simulate 向右箭头按下

编辑:

可以使用Nuget在没有上述链接的情况下安装它:

Install-Package InputSimulator

在 github 上检查它的存储库。

最新更新