Static class in Unity
For something like an AudioManager or GameManager,there's only ONE AudioManager in the entire game world. So to me, it seems logical design-wise to make a Manager class static. Here is my current AudioManager class.
public class AudioManager : MonoBehaviour
{
public AudioClip[] AudioClips;
private AudioSource _audioSourceComponent;
void Start ()
{
_audioSourceComponent = this.GetComponent<AudioSource>();
PlaySound(0);
}
public void PlaySound(int clipIndex)
{
_audioSourceComponent.clip = AudioClips[clipIndex];
_audioSourceComponent.Play();
}
public void PlaySound(int clipIndex, float delayTime)
{
_audioSourceComponent.clip = AudioClips[clipIndex];
_audioSourceComponent.PlayDelayed(delayTime);
}
}
If I do not make this class static, I will have to create a public AudioManager and drag and drop this class every time I want a reference to the methods here that will enable me to play audio. It's just a little more work, and it confuses me. I would like to say AudioManager.PlaySound instead of getting a reference to AudioManager, calling it AudioManager (redundant), and then AudioManager.PlaySound.
Does it make sense design-wise to make it static? I know one problem is, when I tried to make everything static, I could not use GetComponent. Can someone explain this to me?
Answer by nathanlink169 · Jun 27, 2017 at 10:11 PM
GetComponent works on a specific game object - You can only access GetComponent when a class is attached to a game object: static classes cannot be added to a game object.
There are a lot of design theories about whether static classes are good or bad. The general consensus (from what I've seen) is that they're convenient, yet generally bad practice.
That being said, if you're going to make a class static, managers are the perfect ones to make static.
Answer by Mentoliptus · Jun 28, 2017 at 07:00 AM
You could user the Singleton pattern instead of static classes. The component will still be unique across the whole game, but it will be available in the hierarchy and you can use GetComponent.
Your answer
Follow this Question
Related Questions
Static Classes 3 Answers
Static Class Strings not truly null? 1 Answer
Static method performance vs non static 0 Answers
Universal Stats Class for game character/objects 0 Answers
Tips on starting a RPG project (design) 0 Answers