问题
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:
Download zip file on http://inputsimulator.codeplex.com
Unzip that to Assets directory with Your script (C#) in Unity project
Reload MonoDevelop (if is opened)
In script on top write: using WindowsInput;
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