x


Destroying object using his name and raycast

I have a big problem its driving me crazy so im hoping someone will help me :D

I have this game when i press mouse button 1 it instantiates a cube at the position when the ray hits. This part of the program works fine and looks like that :

if(Input.GetButtonDown("Fire1")&& Physics.Raycast (cam.position, cam.forward, hit, 100)!=false )

{

Instantiate(box,point,Quaternion.identity);

}

Then when i press mouse button 2 the object that the ray hits is destroyed. That part works allso well, too well and it looks like this:

if(Input.GetButtonDown("Fire2"))

{
    if (Physics.Raycast (cam.position, cam.forward, hit, 100) )
    {   


        if(hit.transform.gameObject)
        {

        Destroy(hit.transform.gameObject);

        }
    }
}

The problem is when i press mouse button 2 it destroys every object the raycast hits like for example the terrain and i dont want that i want it to destroy only the box and not eany other object and i allso dont want to turn on the Ignore Raycast on eny of my objects.

more ▼

asked May 12 '11 at 12:53 PM

bloodair gravatar image

bloodair
2 1 1 1

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Just check what object you're hitting. For example you could tag your cube as "cube" or "destroyable".

if(hit.transform.gameObject && hit.transform.gameObject.tag == "Cube")
{
Destroy(hit.transform.gameObject);
}
more ▼

answered May 12 '11 at 12:59 PM

GesterX gravatar image

GesterX
2.1k 13 16 37

Yep. Alternatively use gameObject.name.Contains("Cube") to not have to add in a ta :)

May 12 '11 at 01:22 PM Joshua
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1670
x1528
x1092
x764
x193

asked: May 12 '11 at 12:53 PM

Seen: 1605 times

Last Updated: May 12 '11 at 12:53 PM