Reputation: 41
To be more specific, I want to change the color really fastly (like, 60 times a second) and I want to change it from blue, to red, to green, then back again and repeat that over and over
Upvotes: 0
Views: 2116
Reputation: 3829
If you really want to do this, (and I see no practical application for it at all as shown in my javascript demo) the following code will rapidly transition the background colors of the scene (once per frame).
Under camera properties, change the Clear Flags
to Solid Color
. This disables the skybox background and instead just clears the background to a color.
Then, create a new C# behaviour with the following code and attach it to your camera:
public class SkyColorBehaviourScript : MonoBehaviour {
// used to track the index of the background to display
public int cycleIndex = 0;
Color[] skyColors = new Color[3];
void Start () {
// init the sky colors array
skyColors [0] = new Color (255, 0, 0); // red
skyColors [1] = new Color (0, 255, 0); // green
skyColors [2] = new Color (0, 0, 255); // blue
}
// Update is called once per frame
void Update () {
// cycle the camera background color
cycleIndex++;
cycleIndex %= skyColors.Length;
camera.backgroundColor = skyColors [cycleIndex];
}
}
Explanation:
The script has an array skyColors
containing three colors, red, green and blue.
At every update (once per frame) the variable cycleIndex is incremented.
Then, by calling cycleIndex %= skyColors.Length
, whenever cycleIndex is equal to the length of the colors array it resets to zero. (This way if you add more colors to the array it will cycle through them too).
Finally, we change the camera's background color to the color in the array indexed by cycleIndex.
The default frame rate will probably be locked to the refresh rate of your monitor at around 60-100Hz but if you disable vsync you can probably set the target frame rate higher. Note however, that the updates will only run as fast as your graphics hardware can handle, and with vsync off you will experience that ugly "tearing" effect.
Alternative approach via Skybox Tinting
If for some reason you want to change a preset skybox's tint rather than changing the clear color of the active camera, you can use this version of the Update method:
// Update is called once per frame
void Update () {
// cycle the camera background color
cycleIndex++;
cycleIndex %= skyColors.Length;
RenderSettings.skybox.SetColor("_Tint", skyColors [cycleIndex]);
}
Note that this assumes you've applied the skybox to all cameras via RenderSettings as opposed to a per camera Skybox. With this version the active camera's clear flags need to be set to skybox, and you're just changing the tint of the skybox, so some of the skybox texture may still be visible (ie. it won't be a pure red, blue and green background)
Caution: Both techniques are likely to induce an epileptic fit.
Upvotes: 1