如何在单击按钮时模拟按键按下 - Unity [英] How to simulate a key press on button click - Unity

查看:36
本文介绍了如何在单击按钮时模拟按键按下 - Unity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

代码:

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

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

推荐答案

我认为模拟按键不是正确的做法.

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

相反,您应该在点击按钮时调用 PickUp 函数,就像按下 F 键时调用 Pickup 的方式一样.

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

这篇关于如何在单击按钮时模拟按键按下 - Unity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆