Help destroying gameObject on RayCastHit?

Hey all,

This is my first time using raycasts and I’m a total noob at it. I’m sorry for rookiness, but please try to be patient as I’ve been trying to figure this out forever now. Haha! So here is what I am trying to figure out:

I am currently making a horror game and I want the player to constantly be haunted by a monster. I have a system set up where the monster generates in certain areas… The only problem is… I need the monster to disappear 3 seconds AFTER the raycast (from the players viewpoint) hit his collider. I am working on getting a ray projecting from the First Person Controller’s camera at the moment so don’t worry about that (unless it’s necessary.)

Thank you so much! I’ve been working at this for a while and it’s getting frustrating. So thank you so much for your help! It means lots! (Also, I’m willing to provide more information if needed.) Thanks again!

ok, this is pretty simple… first, get the raycast:

function Update () {

    var hit : RaycastHit;

	if (Physics.Raycast (transform.position, transform.forward, hit)) {

next, we want to see if what we hit is the monster. You can use the object’s name or tag to do this easily:

     if(hit.collider.tag == "monster"){

then to destroy:

    Destroy(hit.collider.gameObject);

usually, if you are planning on re-spawning the monster immediately, it would be less costly to just not destroy him at all, but just move him to the new spawn point, as Instantiate() is a costly function.

here’s the whole thing, I think this would work:

function Update () {

    var hit : RaycastHit;

	if (Physics.Raycast (transform.position, transform.forward, hit)) {

                if(hit.collider.tag == "monster"){

                    Destroy(hit.collider.gameObject, 3); 

                }
            }
  }

One final tip, if the monster is meant to be destroyed once in view, this may not work as well as you hope, since the ray is cast directly from the center of the camera… only centering the monster in view is likely to trigger a hit, not sure if that’s what you want…