Advertisement
MariuszPoz

Destroy a GameObject in front of a player in Unity

Jan 11th, 2025
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.20 KB | None | 0 0
  1. // THIS SCRIPT IS EXPLAINED HERE:
  2. // https://unity-is-easy.blogspot.com/2025/01/destroy-gameobject-in-front-of-player.html
  3. // VISIT MY PAGE TO LEARN UNITY :)
  4.  
  5. using UnityEngine;
  6.  
  7. public class DestroyObjectWithCrosshair : MonoBehaviour
  8. {
  9.     public float raycastRange = 10f; // How far the raycast can detect
  10.     public LayerMask targetLayer; // LayerMask to filter what the raycast can hit
  11.     public KeyCode destroyKey = KeyCode.E; // Key to press for destroying
  12.  
  13.     void Update()
  14.     {
  15.         // Create a ray from the camera's position in the forward direction
  16.         Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
  17.         RaycastHit hit;
  18.  
  19.         // Check if the ray hits something
  20.         if (Physics.Raycast(ray, out hit, raycastRange, targetLayer))
  21.         {
  22.             // Debug line to visualize the raycast (optional)
  23.             Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.red);
  24.  
  25.             // If the destroy key is pressed
  26.             if (Input.GetKeyDown(destroyKey))
  27.             {
  28.                 // Destroy the object that was hit
  29.                 Destroy(hit.collider.gameObject);
  30.             }
  31.         }
  32.     }
  33. }
  34.  
Tags: C# Unity
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement