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. public class myRaycastScript : MonoBehaviour {
  5. // Use this for initialization
  6. void Start () {
  7. }
  8. // Update is called once per frame
  9. void Update () {
  10. float xDirection = Input.GetAxis ("Mouse X");
  11. float yDirection = Input.GetAxis ("Mouse Y");
  12. transform.Rotate (-yDirection, xDirection, 0);
  13. CheckIfRayCastHit ();
  14. }
  15. void CheckIfRayCastHit (){
  16. RaycastHit hit;
  17. if (Physics.Raycast (transform.position, transform.forward, out hit)){
  18. print (hit.collider.gameObject.name +"has been destroyed!");
  19. Destroy (hit.collider.gameObject);
  20. }
  21. }
  22. }
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.