Skip to content

Instantly share code, notes, and snippets.

@ItsaMeTuni
Last active October 6, 2017 12:56
Show Gist options
  • Save ItsaMeTuni/f418b78f498cff8acb8f9234debfb613 to your computer and use it in GitHub Desktop.
Save ItsaMeTuni/f418b78f498cff8acb8f9234debfb613 to your computer and use it in GitHub Desktop.
This is a simple class used to bind delegates to a button and invoke that delegate when the button is pressed.
/*
Then attach this class to that object.
How this code works:
Create a button by going into Edit > Project Settings > Input and add a button.
You bind a delegate to that button.
Then when this class's update function is called it will check if the button is pressed.
If it is pressed then the delegate assigned to the button will be invoked.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public delegate void BtnPressed();
/**
This class invokes delegates for buttons when they are fully pressed.
Example to bind a function (recommended to do this at the start function of your class):
\code
InputHandler.AttachFuncToAxis("FooButton", Foo); //Note that you don't need a reference to an InputReference instance since this method is static.
public void Foo()
{
//Do your stuff when the button is pressed
}
\endcode
*/
public class InputHandler : MonoBehaviour {
/**Dictionary that stores delegates assigned to buttons.*/
public Dictionary<string, BtnPressed> delegateList = new Dictionary<string, BtnPressed>();
// Update is called once per frame
void Update ()
{
//Create array of the keys from the delegateList dictionary
string[] delegateListKeys = new string[delegateList.Count];
delegateList.Keys.CopyTo (delegateListKeys, 0);
//Iterate over that array
foreach (string key in delegateListKeys)
{
//If the axis has a value of 1 and its state is false
if (Input.GetButtonDown (key))
{
//Invoke delegate
delegateList[key] ();
}
}
}
/**
Assign a function to a button.
\param button the button name.
\param del the delegate.
*/
public static void AttachFuncToBtn(string button, BtnPressed del)
{
GameObject.FindObjectOfType<InputHandler> ().delegateList.Add (button, del);
}
}
@ItsaMeTuni
Copy link
Author

Here's an axis I created that I use to toggle my game's inventory GUI.
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment