- Home /
Bug caused by Singleton Pattern
This is my audio manager script(singleton)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour {
private static AudioManager _instance;
public static AudioManager Instance {
get {
if (_instance == null) {
Debug.Log ("No AudioManager gameobject was found");
}
return _instance;
}
}
void Awake(){
_instance = this;
}
void Start(){
}
public AudioSource AddAudio(GameObject targetGameObject, AudioClip clip, bool loop, bool playOnAwake, float volume){
AudioSource newAudio = targetGameObject.AddComponent<AudioSource> ();
newAudio.clip = clip;
newAudio.loop = loop;
newAudio.playOnAwake = playOnAwake;
newAudio.volume = volume;
return newAudio;
}
}
and this is my Shoot script(attached to enemy and player object) that calls the singleton
void Awake(){
shootAudio = AudioManager.Instance.AddAudio (this.gameObject, shootClip, loop, playOnAwake, audioVolume);
}
void ShootStuff(){
shootAudio.Play();
}
I set up up this way so that if the ShootScript(or any other script) requires another sound clip to be played, i can just create a new audio source in the script, reference it to the instance of AudioManager's AddAudio function, and a AudioSource component will be created automatically.
The problem arises when i clone the Enemy prefab, the ShootScriptComponent on the cloned Enemy automatically disables when i run the game. Why is it that the Player object that has the same shootScript attached works fine but not for the cloned Enemy, and how should i fix it??? Thanks
$$anonymous$$y guess is that the local reference (this.gameObject) within the prefab is causing the problem. Have a look here for a similar problem http://answers.unity3d.com/questions/45079/instantiated-objects-scripts-not-enabled-not-sure.html
Answer by Pengocat · Jan 18, 2017 at 04:42 PM
You initialize the Singleton in Awake and you use it in Shoot Script in Awake. So you should either setup the "Script execution order" to call the singleton before the shoot or simply call the singleton in the Shoot script in Start and not Awake.
Your answer
Follow this Question
Related Questions
Using static properties that return _instance.variable... 0 Answers
Remnant Empty Game Objects for Static Scripts 1 Answer
Having a static GameObject pointing to a prefab? 1 Answer
Don't render GameObject on load if already hit by player? 1 Answer
Why should I use a game object for non-physical things? 2 Answers