Switch Light On With Up And Down Arrow Keys Using C# Scripts In Unity

Introduction

 
This article demonstrates how to switch a  light on using up & down arrow keys using C# Scripts In Unity.
 
Prerequisites
 
Unity Environment version 2018.4.19f1
 
Create the Project 
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 

Create plane in Unity 

 
First, you have to open the Unity project. Click on the "GameObject" menu in the menu bar. Select the 3D object and click on plane.
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Create the Cube in Scene View
 
Click on the "GameObject" menu in the menu bar. Select the 3D Object. Click on Cube.
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Add the Point Light in Scene View 
 
Add one to your scene by going to GameObject > Light > Point Light .
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Color Change to Point Light in Scene View
 
As you can see, the inspector shows the color change so a light with a blue color is the same as no light at all.
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Create the folder  
 
Right-click on Assets. Select Create >> Folder
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Rename the Folder as Scripts
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 

Create the Scripts

 
Right-click on Assets. Select Create >> C# script
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Rename the Scripts as Switch
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Double click on the Exit script. Write the code as shown below, 
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4. public class Switch: MonoBehaviour {  
  5.     void start() {}  
  6.     void update() {  
  7.         if (Input.GetKey(KeyCode.UpArrow)) this.GetComponent < Light > ().enabled = true;  
  8.         if (Input.GetKey(KeyCode.DownArrow)) this.GetComponent < Light > ().enabled = false;  
  9.     }  
  10. }   
Save the Program
 
Drag and drop the Switch Scripts onto the Point Light .
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Click on the Play button. Select UpArrow Keys and click on the light in scene view. 
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 
Select on DownArrow Keys and click off the light in scene view.
 
Switching Light On UP And Down Arrow Keys Using C# Scripts In Unity
 

Summary

 
I hope you understood how to switch a light on and off using the up and down arrow keys using C# Scripts In Unity.