OnTriggerEnter problem if disactivating gameobjects

Is it really possible to disactive gameObjects when something triggers? Specifically I'm talking about a Camera with an Image Effect enabled.

With the code below, I get the following error:

Destroying object immediately is not permitted during physics trigger and contact callbacks. You must use Destroy instead. UnityEngine.Object:DestroyImmediate(Object) SSAOEffect:DestroyMaterial(Material) (at Assets/Standard Assets/Image Effects (Pro Only)/SSAOEffect.cs:41) SSAOEffect:OnDisable() (at Assets/Standard Assets/Image Effects (Pro Only)/SSAOEffect.cs:49) UnityEngine.GameObject:set_active(Boolean) CameraSplit:OnTriggerEnter(Collider) (at Assets/Scripts/CameraSplit.js:50)

function OnTriggerEnter(other : Collider)
{
    if (other.gameObject.CompareTag ("Player"))
    {
        Camera.main.gameObject.active = false;
    }
}

If I disable the effect before playing the scene, the error doesn't show up immediately, but after some time it does.

Disabling a `GameObject` during a collision/trigger is perfectly fine, however as the error message points out destroying objects immediately during a trigger is not permitted.

When disabling a `GameObject`, any scripts attached to it will get a call to a `OnDisable()` method. In this case the SSAOEffect script's `OnDisable()` is being called, and this subsequently tries to call `DestroyImmediate()` - which spawns the error message.

The easiest solution would be to delay the deactivation until the next `Update()`, in which case you're guaranteed not to be inside collision/trigger updates.

I'll answer my own question because I did something that fixed my problem. If someone wants to add a more detailed answer, feel free.

I continued working on it. I wanted to disable the Camera and AudioListener components as soon as the player entered the trigger zone.

I added

var mainCamera : Camera;

and with the OnTriggerEnter, I did:

function OnTriggerEnter(other : Collider)
{
    if (other.gameObject.CompareTag ("Player"))
    {
        mainCamera.enabled = false;

        mainCameraAudioListener = mainCamera.GetComponent(AudioListener);
        if (mainCameraAudioListener.enabled == true)
        {
            mainCameraAudioListener.enabled = false;
        }
    }
}

With this I could start the game with those mainCamera components enabled, and they would be disabled (enabled = false) when I got into the trigger zone. After leaving and entering the same zone again, I would get no errors at all. Problem fixed.

Just a curiosity: Why does `mainCamera.enabled = false;` works and

if (Camera.main.enabled == true)
{ 
    Camera.main.enabled = false;
}

doesn't? This seems to be almost the same.