Introduction
In this article, we discuss using a dropdown menu in C# to change the background color with a switch statement in Unity.
Prerequisites
Unity environment version 2018.4.19f1
Create the Project
Click on the main camera. The camera Inspector displays Click on Clear Flags Option Select the Solid Color in the scene view.
First, you have to open the unity3D project. The unity window is like this. Select the GameObject menu in the menu bar. Select UI and pick the Dropdown option.
Select the canvas and click on the dropdown. The inspector displays Select the Option and Add the colors name in Unity.
Create the Scripts
Right-click on Assets. Select Create >> C# script
Rename the scripts as ChangeBackgroundColors
Double click on the ChangeBackgroundColors script. Write the code like shown below:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- public class ChangeBackgroundColors: MonoBehaviour {
- public Camera cam;
- public Dropdown mydropdown;
-
- void Update() {
- switch (mydropdown.value) {
- case 1:
- cam.backgroundColor = Color.red;
- break;
- case 2:
- cam.backgroundColor = Color.blue;
- break;
- case 3:
- cam.backgroundColor = Color.green;
- break;
- }
- }
- }
Save the Program.
Create the Empty GameObject
Select the Game Object >> Create Empty GameObject.
Rename the Empty Game Object as DropdownManager
Drag and drop the ChangeBackgroundColors script onto the Dropdown Manager.
Click on the Play button. Select a color mode in run time.
For runtime, select the color red as the background.
Runtime select the color as blue for the background.
For runtime, select green as the background.
Summary
I hope that you understood how to use a C# Dropdown menu to change the background color with a switch Statement in Unity.