Deleting an object with raycast

So I know I’ve seen the answer to this question, so I’ll take this down once I have an answer. But I’m trying to get it once touched by a raycast the object it contacts dissapears for (x) seconds, then reappears. Not sure how to go about this.

Here’s what I’ve got:

function Update()
{
 var up = transform.TransformDirection(Vector2.right);
 var hit : RaycastHit;    
 Debug.DrawRay(transform.position, up * 10, Color.green);
 
   
    if(Input.GetButtonDown("Fire1"))
    {   
        Shoot();
         if (Physics.Raycast (transform.position, up , hit, 200))
    	{
            if (hit.collider.gameObject.tag == ("Enemy")) 
            	{
            		
            		hit.collider.enabled = false;
            		Debug.Log ("Start");
            		WaitForSeconds(3);
                    Debug.Log ("Stop");
            		hit.collider.enabled = true;


                    //Destroy(hit.collider.gameObject);
            		/*hit.renderer.enabled = false;
            		WaitForSeconds(3);
            		hit.renderer.enabled = true;
                    Debug.Log("Success");
                    */
                }
        }
   }
}

Destroys not what I want, because I want the object to come back. Unity gives me errors when I try to use renderer, and what I don’t have commented out at the moment does absolutely nothing except for display the log. I would assume that’s because the code is useless, but I was just trying to figure it out myself before I turned to UA. But here I am :smiley: :frowning:

In terms of hiding the object, you want renderer. To get to the renderer from a RaycastHit you can do:

hit.collider.renderer.enabled = false;

In addition you need to use ‘yield WaitForSeconds(3.0);’ to wait, but you cannong use a ‘yield’ in Update(). So you want to make the code that hides and displays the object a separate function:

function HideAndShow(hit : RaycastHit) {
    hit.collider.enabled = false;
    hit.collider.renderer.enabled = false;
    yield WateForSeconds(3.0);
    hit.collider.enabled = true;
    hit.collider.renderer.enabled = true;
}

And you would replace lines 16 - 20 with:

HideAndShow(hit);

Note the code turns off the collider as well as the renderer so that if you shoot while the object is hidden, you will not be able to hit the hidden object.

when I use raycast I put the info that I get from the ray into my hit.
it seems you were trying to do the same however you missed 1 keyword : “out”.

like this:

if (Physics.Raycast (transform.position, up , out hit, 200))

I don’t know if this solves your problem but who knows :slight_smile:

else you wont be able to use hit in your other if statements and such since hit would equal null instaid.