using UnityEngine; using System.Collections.Generic; public class RaycastDemo : MonoBehaviour { public Vector2 rayStart; public Vector2 rayEnd; void Update() { RaycastHit2D[] hits = Physics2D.GetRayIntersectionAll(rayStart, rayEnd); ListhitObjectNames = new List (); foreach (RaycastHit2D hit in hits) { hitObjectNames.Add(hit.collider.gameObject.name); } Debug.Log("Objects hit: " + string.Join(",", hitObjectNames.ToArray())); } }
using UnityEngine; public class RaycastDestroy : MonoBehaviour { public float rayLength; public LayerMask layerMask; void Update() { RaycastHit2D[] hits = Physics2D.GetRayIntersectionAll(transform.position, Vector2.right, rayLength, layerMask); foreach (RaycastHit2D hit in hits) { Destroy(hit.collider.gameObject); } } }This example creates a script that destroys any 2D physics objects that intersect with a ray cast from the position of the script's game object to the right. The method Physics2D.GetRayIntersectionAll is used with a specified ray length and layer mask to detect all 2D collider objects that intersect with the ray. Any hit object is then destroyed using the Destroy method. Package Library: The Physics2D GetRayIntersectionAll method is part of the Unity Engine API which is included in the UnityEngine package. No additional libraries or packages are necessary to use this method.