Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // THIS SCRIPT IS EXPLAINED HERE:
- // https://unity-is-easy.blogspot.com/2025/01/destroy-gameobject-in-front-of-player.html
- // VISIT MY PAGE TO LEARN UNITY :)
- using UnityEngine;
- public class DestroyObjectWithCrosshair : MonoBehaviour
- {
- public float raycastRange = 10f; // How far the raycast can detect
- public LayerMask targetLayer; // LayerMask to filter what the raycast can hit
- public KeyCode destroyKey = KeyCode.E; // Key to press for destroying
- void Update()
- {
- // Create a ray from the camera's position in the forward direction
- Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
- RaycastHit hit;
- // Check if the ray hits something
- if (Physics.Raycast(ray, out hit, raycastRange, targetLayer))
- {
- // Debug line to visualize the raycast (optional)
- Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.red);
- // If the destroy key is pressed
- if (Input.GetKeyDown(destroyKey))
- {
- // Destroy the object that was hit
- Destroy(hit.collider.gameObject);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement