How exactly does Input.GetButtonDown and Input.GetButton (and similar functions) work?
I want to implement something similar, but instead of listening for a key click, it instead listens for a UI button click. I’ve looked into events, but I’m not sure if that’s really it. Thanks!
Edit: Sorry, I should have been clearer with my question. This is more like what I’m looking for:
Say I have this kind of UIManager
public static class UIManager {
public static bool GetUIButtonClick() {
// some code here
}
}
which is used like so:
void Update() {
if (UIManager.GetUIButtonClick()) {
// do something
}
}
and the UIManager.GetUIButtonClick() would return true during the frame the UI button is clicked.
Is there something that could do that already? If not, I guess I could just have a bool variable toggled by the UI button, which is probably how the Input.GetButtonDown works, but I’m just making sure. Thanks for being patient with me!
Are you using the unity visual UI ?
If yes you can assign a method in the inspector by adding a button component and a assign the method you wish to call on there.
Tutorial: UI Button - Unity Official tutorials - YouTube
One very simple way is to use what the Editor gives you.
Make a script, give it a method that does what you need to happen when your UI button gets clicked.
Now, attach the script to something in your scene (could be a manger or even the Button itself) and add an event to the buttons “OnClick” box. Drag and drop the component with your method in it and select the method in the drop down menu to the right.
Every time your button gets clicked, the method will be called.
I’ve finally implemented something that I want, although it acts more like Input.GetButtonUp() instead. Here’s the code:
public bool isUIButtonClicked = false;
public bool GetUIButtonClick() {
if (isUIButtonClicked) {
isUIButtonClicked = false;
return true;
}
return false;
}
// This is what the UI button runs when it is clicked
public void OnUIButtonClick() {
if (!isUIButtonClicked)
isUIButtonClicked = true;
}
and here is how it is used:
void Update() {
if (UIManager.GetUIButtonClick())
Debug.Log("Clicked!");
}
So it doesn’t even need events at all! Although this is the simplest I can think of, so maybe events are used if you also wanna do GetUIButtonDown and GetUIButtonHeld.