- Home /
How do you make it so that pressing an on-screen button "presses" a key in C#, Unity 5.1.1f?
I am creating a game as a first project and I want to know to make it so that when I press a button on the screen, it sort of "links" to a key and acts as if it pressed it. Say, for example, I want to press the key "w" and the key "s." How would I do that?
I am using Unity 5.1.1f, and utilizing the new UI system. Please help, and thank you in advance.
Answer by Cherno · Sep 20, 2015 at 08:31 PM
Do it like this:
If you check for keyboard input and the key is pressed, then you call a seperate function. Now you call this function when the on-screen button is clicked as well. Done!
void Update() {
if(Input.GetKeyDown(KeyCode.Space)) {
MyFunction();
}
}
void MyFunction() {
Debug.Log("MyFunction has been called!");
}
Answer by EnriqueL · Sep 21, 2015 at 11:35 AM
you can use the UI event system, inside the button you have an event trigger where you can cal any function with the on click trigger, or you can add to your script a function that react with the click, just add:
using UnityEngine.EventSystems;
public class nameClass : MonoBehaviour, IPointerClickHandler {
public void OnPointerClick (PointerEventData eventData)
{
//your code on click
}
}
And attach it to the button gameobject or the object.
I hope it helps!