Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate a key press on button click - Unity

Tags:

c#

unity3d

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");
    }
} 
like image 888
Casper Round Avatar asked Feb 22 '18 14:02

Casper Round


People also ask

How do you simulate button press in unity?

You can simulate a button click by sending a NavigationSubmitEvent with your button as the target. Code (CSharp): using (var e = new NavigationSubmitEvent() { target = WButton } )

How do I know if my Unity button is clicked?

A button should only react once it is clicked, which is why it has the onclick . Unity is already internally checking if a button is clicked by using its EventSystem and a series of GraphicalRaycasts .


1 Answers

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() ;
}
like image 56
Hellium Avatar answered Sep 24 '22 15:09

Hellium