Change background color through script?

Can this be done? I tried attaching this script to my camera:

var newColor = Color (0.2, 0.3, 0.4);

function Update () {
	Camera.backgroundColor = newColor;
}

but get an error about needing to access non-static member “backgroundColor”, which is completely Greek to me :shock: Any ideas?

Camera.backgroundColor

Is trying to access a class variable for the Camera class, or a variable that is shared by all instances of that class. Often (not sure about all languages) this is refered to as a “Static” variable. In this case, it would be a background that all cameras used. However, each camera has its own background. What you need to do is get the reference of the camera that you want to change the background. Sounds like you currently only have one, so

Camera.main.backgroundColor = newColor;

will probably work. In this case, “main” is a class variable of the Camera class that returns the camera instance that has a tag of “Main Camera”. The “.background” part then refers to the “main” camera that was returned.

2 Likes

Thanks ifrog, although that didn’t work, it did make me dig through a different section of the docs and I found something that got me going. Here’s the revised script:

var newColor = Color (0.2, 0.3, 0.4);

camera.clearFlags = CameraClearFlags.Color;

function Update () {
	camera.backgroundColor = newColor;
}
1 Like

Yes, if the script is attached to camera, then changing Camera (which is a class name) to camera (which is the camera itself on the current game object) gets it compiling.

You also need to set the camera to actually clear to color (instead of skybox), either from Unity, or from script just like you did.

heres a script to change the background via HSV controls

#pragma strict
var Hcol :float;
var Scol :float;
var Vcol :float;

//var SPercent :float;
//var VPercent :float;

function Start () {

// Hcol = Random.value;
//Scol = Random.value ;
//Vcol = Random.value + VPercent / 100 ;

Camera.main.backgroundColor = HSVtoRGB(Hcol,Scol,Vcol);
}

function Update () {
Camera.main.backgroundColor = HSVtoRGB(Hcol,Scol,Vcol);
print (HSVtoRGB(Hcol,Scol,Vcol));
print (HSVtoRGB(Hcol,Scol,Vcol));
}

function HSVtoRGB(h : float, s : float, v : float) {

h=h%1;
s=s%1;
v=v%1;
var r : float;
var g : float;
var b : float;
var i : float;
var f : float;
var p : float;
var q : float;
var t : float;
i = Mathf.Floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
return Color(r,g,b);
}