ArgumentException: get_fog can only be called from the main thread(C#)

I don’t know why I get this problem. All I wanted to do was activate fog with a specific fog color then suddenly its values jump to insane Color ranges.

Target fog color

Color(66.0f,79.0f,72.0f,255.0f);

Actual fog color Value shown while scene is playing(It’s white in color)

Color(16830.0f,20145.0f,18360.0f,255.0f);

Here’s the code

using UnityEngine;
using System.Collections;

public class UnderWaterFX : MonoBehaviour {
	public int Water = 3;
	Color fogColor = new Color(66.0f,79.0f,72.0f,255.0f);
	public Color fcolor = RenderSettings.fogColor;

	void Start () {
}

	void Update () {

    if(this.transform.localPosition.y < Water)
    {
		RenderSettings.fog = enabled;
        RenderSettings.fogColor = fogColor;

        RenderSettings.fogDensity = 0.1f;

    }

    else

    {
		RenderSettings.fog = !enabled;
    }
	
	}
}

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.

What’s the fix to this?

try setting fcolor = RenderSettings.fogColor; within Start(). You are trying to call a function from a field initializer, as it says in the error log.

Hey Tatsunomi, I think I can help you out here.

There are actually two issues that need to be addressed to get you going. The first and most important is the error. What it is telling you is that the RenderSettings.fogColor variable cannot be accessed outside of the function scope. So instead of defining your fColor variable at declaration, just do that in your start function, like this:

public Color fColor;

void Start(){
    fColor = RenderSettings.fogColor;
}

Second issue is that the Color constructor takes floats from 0 to 1, not ints from 0 to 255, so Color(1.0f, 1.0f, 1.0f, 1.0f) will result in solid white. So what you can do is simply divide each of your 0-255 values by 255, this will give you the 0-1 value needed by Color() so for your fogColor constructor, try this:

Color fogColor = new Color(0.2588f, 0.3098f, 0.2324f, 1.0f);