- Home /
Can i fire off a function if ANY button is pressed?
basically, I have a function which plays a click sound, and at the moment I manually add MenuClick(); to each one of the buttons calls to get the desired effect., but I've started missing loads, just wondered if there's any way to make this a lot easier.
eg. if(anybuttonpressed) playclick; [EDIT] And by button i mean UI button not keyboard.
Answer by Vega4Life · Aug 20, 2019 at 05:34 PM
Here is an idea - not sure if its helpful. You could create a buttonController, that has an OnButtonClick method - that takes itself as an argument. The buttonController also has an enum for all the types of menu buttons. This allows for a single method that all buttons are passed into - thus all of them will always do a button sound, thus not worrying about accidentally not hooking one up Then you can parse out which button was clicked with a switch or however.
Here is an example: I created 4 UI buttons. Added the below ButtonController to them. Linked up the onClick of the UIbutton to the buttonController 'OnButtonClick' method - also linked the script as the argument.
I forgot to mention to also set the button type (start, stop, etc) in the inspector for each button. In your case it would be whatever button types you have. :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This goes on the Button object. Link this object to the UI Button 'OnClick()'
/// Also, link this script as the argument
/// </summary>
public class ButtonController : MonoBehaviour
{
public enum ButtonTypes { Start, Stop, Left, Right };
[SerializeField] ButtonTypes buttonType;
public void OnButtonClick(ButtonController bc)
{
// All buttons filter through here, so do button sound
// PlayClick();
switch (bc.buttonType)
{
case ButtonTypes.Stop:
// Do stop button things
break;
case ButtonTypes.Start:
// Do start button things
break;
case ButtonTypes.Left:
// Do left button things
break;
case ButtonTypes.Right:
// Do right button things
break;
}
}
}
Maybe it gives you some idea to handle your situation.
Thanks for the reply, ill look into this when i get back to it tonight, appreciate the effort .
Your answer
Follow this Question
Related Questions
How to mute my volume 2 Answers
Gui Playing Audio Trouble 1 Answer
How do I get Button to play a random sound in Unity 5.0? 2 Answers
Audio problems with unity after reloading my game from the main menu 1 Answer
I Need a script for a guitexture enableing a spotlight and play a sound when pressed 1 Answer