I have a scene with 5 cameras that can be switched between. In the Script that is attached to the MainCamera there is an array of all of the cameras as shown below:
public Camera[] allCams;
I also have a function to set the active Camera that I want to use:
public void SetCamera( int camNum )
{
foreach( Camera cam in allCams ) // disable all of the cameras and listeners
{
cam.enabled = false;
cam.GetComponent<AudioListener>().enabled = false;
}
allCams[ camNum ].enabled = true; // enable the selected camera
allCams[ camNum ].GetComponent<AudioListener>().enabled = true;
renderCam = camNum; // save the current camera index
}
The method works fine for switching cameras, but for some reason it doesn’t seem to disable the audio listeners. Despite calling this method from the Start() method of the script attached to the scene’s MainCamera, and even going gonzo on it and putting calls to the function into the Update() method, I still repeatedly get the following message"
How do I fix this? Any help would be greatly appreciated.
Instead of disabling the listener, remove it completely, then re-add it to whichever one you’re switching to.
The Unity folks should seriously make listeners more savvy. Splitscreen just doesn’t sound right without an insanely complex, scripted solution for multiple cameras.
Thanks Tuah. I tried to implement this, and it seems simple enough to destroy the AudioListener component on each of the cameras. However, even though I thought that a Camera was a GameObject, my attempts to invoke. cameraObject.AddComponent() fail as the function is unrecognized for the camera (where cameraObject is defined as “public Camera cameraObject;”
What am I doing wrong? How do I add the component to a know Camera object?
I’ve just been working on this myself. The easiest way is to create a GameObject that is always in the scene with the one and only AudioListener on it. Then when switching cameras, set the parent of that object to the camera. All you have to do then is align the transform to that camera.
So something like this.
public Transform _AudioListener;
public void SetCamera( int camNum )
{
allCams[renderCam].enabled = false;
allCams[ camNum ].enabled = true; // enable the selected camera
// attach audio listner to camera
_AudioListener.parent = allCams[ camNum ].transform;
// align audio listener to camera (do after parent)
_AudioListener.localPosition = Vector3.zero;
_AudioListener.localRotation = Quaternion.identity;
renderCam = camNum; // save the current camera index
}
And TADA! One listener, multiple cameras. Hope this helps.
hi arcane…thanks for the script. first of all i’m a beginner in unity as well as scripting. like you said, i’ve assigned that on an empty game object and it’s showing an error:
error CS0103: The name “allCams” does not exist in the current context