Change background type from Solid Color to SkyBox dynamically C#

3.4k views Asked by At

I have a scene that has to have the background as solid color.

But when I activate a given use case I need it to have a skybox.

I know I can do this on the editor via: enter image description here

But I'd like to change it dynamically in C#.

There's no property or field for this in C# default Camera script.

Is it possible to do in Unity?

1

There are 1 answers

0
Adrian Babilinski On

To change between rendering a skybox and a solid color, set the camera's clearflags

Example Methods:

public void RenderSkybox(Camera targetCamera = null)
{
    if (targetCamera == null)
    {
        //Get reference to main camera if no camera is passed
        targetCamera = Camera.main;
    }
    //set camera to render the skybox
    targetCamera.clearFlags = CameraClearFlags.Skybox;
}

public void RenderColor(Color color, Camera targetCamera = null)
{
    if (targetCamera == null)
    {
        //Get reference to main camera if no camera is passed
        targetCamera = Camera.main;
    }

    targetCamera.clearFlags = CameraClearFlags.SolidColor;
    targetCamera.backgroundColor = color;
}

Example Usage:

IEnumerator Start()
{
    //reference the main camera
    var targetCamera = Camera.main;
    
    //Set the camera to render blue as the background color
    RenderColor(Color.blue, targetCamera);
    
    //wait two seconds
    yield return new WaitForSeconds(2);
    
    //Set the camera to render the skybox
    RenderSkybox();

}