That’s not the answer. Disabled objects should be able to be accessed. Only destroyed objects should cease to be assessible.
Moreover, if you can’t access it, how can it be enabled again? The camera object is still there with its components until it’s destroyed, so it’s no point for banning its access.
And the problem is that this extends to all parts of the entire solution, all codes with a “Camera.main.” will report a null reference. So it’s not about how you get the component first before disabling.
It may depend on how Unity works inside. If Camera.main is in fact a kind of function, with a private array, listing all enabled cameras in the right order and always returning the first element, if there are no more enabled camera, it would then have nothing to return.
Just suppositions. If someone knowledgeable could answer…
with 2 cameras in the scene tagged “maincamera” it will disable the first camera, then disable the audio listener on the scecond camera in this script.
I guess the problem here is, for whatever codes you added to the following functions, you need to explicitly detect your camera’s availability, or else havoc situation may be resulted,
Update(), LateUpdate(), FixUpdate(), OnGUI()…and the like.
Before you use any camera function inside such functions you need to add the following
void OnGUI()
{
if (!GameObject.Find("MyCam1").GetComponent<Camera>().enabled)
return;
}
It is because all those functions are called on a timely basis, and whenever your camera is diabled, any reference to your camera and its components inside these functions will throw a nullreference error.
You could store a ref to your camera (more efficient to do this anyway):
function Awake() {
var defaultMainCamera : Camera = Camera.main;
}
Provided there’s a MainCamera camera active when an object with that function is created, you won’t have to worry about whether the Camera.main exists or no.
Also, it seems like the following only works when it doesn’t actually do anything: