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 Sphere

Step 1

First, you have to open the Unity project. Go to File>> New scene. Create a new scene like the following.

Click on GameObject menu in the menu bar. Select 3D object and pick the Sphere option.

Create more spheres. Now, I have created 8 spheres in the scene view. I will change the sphere color into green and red.

Set the camera so as to display all the spheres in Game View.

Create Script

Step 2

Right click on the Assets panel, select Create, and pick the C# script.

C# script will be added into the Assets. Rename the script as myRaycastScript. Drag and drop the script into Main camera.

Click on the “Play” button. The spheres will be displayed in the Game View.

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.   
  30.     }  
  31. }  

Save the program.

Click on the Play button. The spheres will be displayed.

Move the mouse into any particular sphere. The sphere will be destroyed. The sphere will be destroyed with the hierarchy panel. The message will be displayed into the Console View.

The sphere 7 will be removed into the Game View.

Destroy all the spheres and it will display the message into the console view.

Summary

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

Up Next
    Ebook Download
    View all
    Learn
    View all