Need Help Destorying Specific Object C#

I’m making a 3D platformer and I’m trying to use a raycast to destroy things like blocks and enemies. I’ve had some success with using triggers for this but it seems to not work as well as it should so I thought a raycast might work better. I’ve managed to destory my PickUpObj, but it also destroys all PickUpObj’s in the scene. I would like it to only destroy the one that I’m hitting. Here us my code:

Vector3 upward = transform.TransformDirection (Vector3.up) * 10;
        Debug.DrawRay (transform.position, upward, Color.green);


if(Physics.Raycast(transform.position, upward ,out hit)){
       if(hit.collider.gameObject.tag == "pickup"){
       Destroy(GameObject.Find("PickUpObj"));
       }

GameObject.Find gives you a reference to some object named PickUpObj in the scene - and it doesn’t care where it finds it. What you need is a reference to the specific one you hit, and you have it - you’re already using it in the line above! Try Destroy(hit.collider.gameObject);

1 Like

Friggin’ awesome! Thanks! I’m glad that was such an easy fix. I had a feeling the answer was in that line somewhere I just didn’t know what it was. I’m getting there!

Why don’t you just get the GameObject you hit from the hit.

hit.collider.gameObject? Using GameObject.Find(string) is very expensive.

1 Like

By the way, how do I make my code appear in that grey box that every else’s does?

Thanks Polymorphik! I actually just started to learn raycast yesterday so a lot of it is still Greek to me. :stuck_out_tongue:

your code here

(Just without that extra space)

Perfect. Thanks!