Raycasting In Unity

Introduction

 
This article demonstrates how to create an object and destroy it using scripts in Unity.
 
Prerequisites
 
Unity Environment version 5.6.1
 

Create a Sphere

 
Step 1
 
First, you have to open the Unity project. Go to File>> New scene. Create a new scene like the following.
 
Raycasting In Unity
 
Click on the GameObject menu in the menu bar. Select the 3D objects and pick the Sphere option.
 
Raycasting In Unity
 
Create more spheres. Now, I have created 8 spheres in the scene view. I will change the sphere color into green and red.
 
Raycasting In Unity
 
Set the camera so as to display all the spheres in Game View.
 
Raycasting In Unity
 

Create Script

 
Step 2
 
Right-click on the Assets panel, select Create, and pick the C# script.
 
Raycasting In Unity
 
C# script will be added to the Assets. Rename the script as myRaycastScript. Drag and drop the script into the Main camera.
 
Raycasting In Unity
 
Click on the “Play” button. The spheres will be displayed in the Game View.
 
Raycasting In Unity
 
Go to the mono-developmentUnity. Write the code as given below.
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class myRaycastScript : MonoBehaviour {  
  6.       
  7.     // Use this for initialization  
  8.     void Start () {  
  9.           
  10.     }  
  11.       
  12.     // Update is called once per frame  
  13.     void Update () {  
  14.   
  15.         float xDirection = Input.GetAxis ("Mouse X");  
  16.         float yDirection = Input.GetAxis ("Mouse Y");  
  17.   
  18.         transform.Rotate (-yDirection, xDirection, 0);  
  19.   
  20.         CheckIfRayCastHit ();  
  21.     }  
  22.             void CheckIfRayCastHit (){  
  23.                 RaycastHit hit;  
  24.                 if (Physics.Raycast (transform.position, transform.forward, out hit)){  
  25.                     print (hit.collider.gameObject.name +"has been destroyed!");  
  26.             Destroy (hit.collider.gameObject);  
  27.                 }  
  28.     }  
  29. }  
Save the program.
 
Raycasting In Unity
 
Click on the Play button. The spheres will be displayed.
 
Raycasting In Unity
 
Move the mouse into any particular sphere. The sphere will be destroyed. The sphere will be destroyed by the hierarchy panel. The message will be displayed in the Console View.
 
Raycasting In Unity
 
The sphere 7 will be removed into the Game View.
 
Raycasting In Unity
 
Destroy all the spheres and it will display the message into the console view.
 
Raycasting In Unity
 

Summary

 
I hope, you understood how to create the object and destroy it using C# scripts in Unity.