I’m having some design-problems when it comes to my ‘global class’.
- I can’t assign anything to the AudioClip property from the inspector because it’s static. So I have no choice but to use the resources folder. Is there no way around this other than singletons? The problem with a singleton is that I get this extra “.Instance” call in my code. Like: GameSettings.Instance.MyClip instead of GameSettings.MyClip.
- I don’t want to use the resources folder. Because I just keep messing around with dragging objects from the “Audio/SFX/” folder to the “Resources/Audio/SFX/” folder. I basically need all of my folder-structures duplicated and move any asset from the regular tree to the Resources-folder-tree if I want to use it through code… Is there no better solution? Like why can’t I just add a reference to an asset on design-time?
public static class GameSettings
{
public const string ButtonClickSFX = ""; // A string is nice but then I must still load the audioclip from the resources folder at some point...
public static readonly AudioClip ButtonClipSFX;// = ??? Can't set through the inspector... Don't want to use the Resources folder either... Also prefer not to use a singleton.
}
I quickly tried to make a generic script to automatically play my audioclip when I press a button (is this not build-in into Unity??) if the button has this script attached. This way I don’t have to edit every single button if I ever change the audioclip’s filename in the future.
However, I remember from C# that attaching something to an event (like: button.onClick +=…) must also have the -= operator called on it when the object is destroyed, otherwise a memory leak is created. Is this handled automatically in Unity5 or must I add it to the monobehaviour’s-destructor somehow?
Though I did notice that the += and -= aren’t even supported for some reason. It requires .AddListener(). Is this not an event? I’m slightly confused here.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[RequireComponent(typeof(AudioSource))] // Probably need only 1 global audiosource for all buttons?
[RequireComponent(typeof(Button))]
public class ButtonAudio : MonoBehaviour {
#region Members
AudioSource audioSource;
Button button;
#endregion
void Awake()
{
audioSource = GetComponent<AudioSource>();
if (audioSource == null) { Debug.LogError("No Audiosource found."); }
button = GetComponent<Button>();
if (button == null) { Debug.LogError("No Button found."); }
//button.onClick += new Button.ButtonClickedEvent(); // Erm...
button.onClick.AddListener(() => PlayAudio());
}
void PlayAudio(object sender)
{
// Play audio here. Get it from the GameSettings.
}
}