How to switch cameras without overlapping listeners

Hello,

So I’m trying to set it up so that when the main character dies (using 3rd person camera that is part of the character hierarchy) a new camera will be instantiated that rotates around the point where the main character died. My current script is set up as follows:

public class MechDeath : MonoBehaviour
{
    public GameObject explosionPrefab;
    public GameObject firePrefab;
    public GameObject killCam;

    public bool usesFire = true;

    private UnitHealth unitHealth;
    private Vector3 offset = new Vector3(0, 2, 0);
    private bool alreadyCalled = false;

    void Start()
    {
        unitHealth = GetComponent<UnitHealth>();
    }


    void Update()
    {
        if (unitHealth.CurrentHealth() <= 0)
        {
            KillMech();
            alreadyCalled = true;
        }
    }

    void KillMech()
    {
        if (!alreadyCalled)
        {
            Instantiate(explosionPrefab, transform.position + offset, transform.rotation);
            if (usesFire)
            {
                Instantiate(firePrefab, transform.position, transform.rotation);
            }

            Instantiate(killCam, transform.position, Quaternion.identity);
            Destroy(gameObject, 0.2f);            
        }
    }
}

With this setup, when the character dies, there is usually about 22 frames where both the MC camera and the killCam exist at the same time which prompts the error: “There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene.” So is there a proper way to switch cameras in such a situation? As always, thank you very much for your help!

Simple. Right before you switch cameras, disable the listener component on the camera, then instantiate the new one, and do the same if you switch back again.

Something like this but cache your references:

Camera.main.GetComponent<AudioListener>().enabled == false;

That’s untested - but if I remember correctly that should work.

Ah, very clever. I guess I was just expecting there to be a more clean way to do it, but I think that should work, I’ll try it in a bit. Though I think I might swap out the comparison operator for assignment :wink:

Camera.main.GetComponent<AudioListener>().enabled = false;