Change the background color of a scene

Page update date :
Page creation date :

Verification environment

Windows
  • Windows 11
Unity Editor
  • 2020.3.25f1
Input System Package
  • 1.2.0

Prerequisites for this tip

The following settings have been made in advance as a premise for the description of this tip.

About scene background colors

The background color of a scene in Unity is not owned by the scene, but is the camera setting. If you select From Main Camera the hierarchy, the background color is displayed at the same time as the camera preview.

About changing the background color

The Camera component has a "background" from which you can change it.

Change the background color programmatically

After clicking the button, move the program and try to change the background color. See the Button Tips for how to move the button click process. Only the program is described here.

using System.Linq;
using UnityEngine;

public class ButtonEvent : MonoBehaviour
{
  public void OnClick()
  {
    // カメラコンポーネントを取得
    var cameraObject = gameObject.scene.GetRootGameObjects().FirstOrDefault(obj => obj.GetComponent<Camera>() != null);
    var camera = cameraObject.GetComponent<Camera>();

    // 背景色を変更
    camera.backgroundColor = new Color(0.3f, 0.0f, 0.1f);
  }
}

Since we will be changing the background color of the camera, we will first get the camera component. If you attach a script to the camera object beforehand or have a camera as a field, the code will be a little shorter, but gameObject This time, I am searching and referring to it from linked scene to. Any code that can eventually get the camera component is fine.

Camera Once you have the component, set backgroundColor the Color property to determine the color. Color You can set the constructor to any number or set the predefined red and blue .

Operation check

Try running it and see if it changes color.