Skip to main content

Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines

How to destroy gameObjects with specific tag when it touches a ray?

A topic by HeartyCod3r created Jul 27, 2023 Views: 105 Replies: 3
Viewing posts 1 to 2
Submitted (1 edit)

Im using Unity and developing a game,which when a laser hit the object with the tag "gems" and it will be destroyed.Here's my code:

```

//Handle ray reflection

Ray ray = new Ray(position, direction);

            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, laserMaxLength, reflectionMask))

            {

                Vector3 reflectDirection = Vector3.Reflect(direction, hit.normal);

                lineRenderer.positionCount = ++pointCount;

                lineRenderer.SetPosition(pointCount - 1, hit.point);

                position = hit.point;

                direction = reflectDirection;

                Check(hit.collider.gameObject);

            }

            else

            {

                lineRenderer.positionCount = ++pointCount;

                lineRenderer.SetPosition(pointCount - 1, position + direction * laserMaxLength);

                break;

            }

//Handle Collision with Gems

            if (Physics.Raycast(ray, out hit)) {

                if(hit.collider.gameObject.tag=="gems"){

               Destroy(hit.collider.gameObject);

                }

              }

```


however it is not working!my gem contains a mesh collider with Convex set to true only.

Pls help!

Submitted

It might be with the order of your ray casts. You are performing two separate ray casts, one for reflection and one for checking gem collisions, which could cause this. Instead, you should combine the reflection check and gem collision check into a single ray cast.

Submitted

just figured out im using the wrong layer,now im changing the layer and everything looks perfect!Thanks for your help!

Submitted

No problem! Glad you fixed it!