3
\$\begingroup\$

I have created a basic sound manager according to this unity tutorial (https://unity3d.com/learn/tutorials/projects/2d-roguelike/audio). However, I need it to work for multiple players over the network, and it doesn't make sense for them all to be playing the same sounds. E.g. If a player loses, it should play the gameover sound, but the other player(s) should remain in the game and continue playing the game sound. But the current behavior is that once a player loses, everyone gets the gameover sound.

By the tutorial, I currently use a single instance within the SoundManager class. I think I need multiple SoundManager instances, each associated with a client. What's the best thing to attach the SoundManagers too? Or is there a different best practice for managing sounds for multi-player games?

Here's the code for my sound manager:

using UnityEngine;
using System.Collections;

public class SoundManager : MonoBehaviour {

    public static SoundManager instance = null; 

    public AudioSource effects;
    public AudioSource music;

    void Awake ()
    {
        if (instance == null)
            instance = this;
        else if (instance != this)
            Destroy (gameObject);
        DontDestroyOnLoad (gameObject);
    }

    public void playSoundEffect(AudioClip clip) {
        effects.PlayOneShot (clip, 1f);
    }

    public void setBackgroundMusic(AudioClip clip) {
        music.clip = clip;
        music.Play ();
    }
}
\$\endgroup\$
2
\$\begingroup\$

This turned out to be much easier than I imagined. Don't know if this is a best practice, but you can just attach the sound manager to an empty game object and get a client instance of it via GameObject.Find("Name of your sound manager").GetComponent<SoundManager>(). You can do this inside of public override void OnStartLocalPlayer (). Get rid of the instance variable inside the class.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.