ArgumentException: get_fog can only be called from the main thread

i get this error. does anyone know how to fix it?

ArgumentException: get_fog can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

here is the script

//This script enables underwater effects. Attach to main camera.

//Define variables
var underwaterLevel = 7;

//The scene's default fog settings
var defaultFog = RenderSettings.fog;
private var defaultFogColor = RenderSettings.fogColor;
private var defaultFogDensity = RenderSettings.fogDensity;
private var defaultSkybox = RenderSettings.skybox;
var noSkybox : Material;

function Start () {

    //Set the background color
    camera.backgroundColor = Color (0, 0.4, 0.7, 1);
}

function Update () {
    if (transform.position.y < underwaterLevel) {
        RenderSettings.fog = true;
        RenderSettings.fogColor = Color (0, 0.4, 0.7, 0.6);
        RenderSettings.fogDensity = 0.04;
        RenderSettings.skybox = noSkybox;
    }

    else {
        RenderSettings.fog = defaultFog;
        RenderSettings.fogColor = defaultFogColor;
        RenderSettings.fogDensity = defaultFogDensity;
        RenderSettings.skybox = defaultSkybox;
    }
}

Searching the error revealed two similar issues:

Eric's answer is more relevant for your Unityscript:

Code outside of functions should stick to declaring types or specific values only. Instead of

private var attackTime = Time.time;

use

private var attackTime : float;

Basically, you can't store 'RenderSettings.###' from outside of a function. Set the values in function Start() and the error should disappear.


Your code should look something like this. It's untested, but I checked the types against the RenderSettings Script Reference, so it should be fine. Please comment back if you have trouble.

//The scene's default fog settings
var defaultFog : bool;
private var defaultFogColor : Color;
private var defaultFogDensity : float;
private var defaultSkybox : Material;
var noSkybox : Material;

function Start () {

    defaultFog = RenderSettings.fog;
    defaultFogColor = RenderSettings.fogColor;
    defaultFogDensity = RenderSettings.fogDensity;
    defaultSkybox = RenderSettings.skybox;

    //Set the background color
    camera.backgroundColor = Color (0, 0.4, 0.7, 1);
}