- Home /
Click to destroy object
I need a script so that when the mouse clicks directly on an object, it is destroyed. Here is what I've got so far..
var clicked : boolean = false; var hit : RaycastHit; function Update() { if(Input.GetMouseButtonDown(0) && collider.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),hit, Mathf.Infinity)) { Destroy(gameObject,0);
} }
Any ideas/advice?
P.S. Sorry I've been putting up so many questions this evening. This is the last one. I hope.
Use ray casting from the user, and check what it hits, make that equal to an object var, and then destroy that var... And just loop it, and have a if it's not there, make it equal to null, and just put it in update function... if this makes sense haha.
Answer by Eric5h5 · Mar 23, 2011 at 08:58 PM
Put this script on the objects:
function OnMouseDown () {
Destroy(gameObject);
}
Exactly what i wanted.. cant we also tell.. if( Input.Get$$anonymous$$ey( "Fire1" ) ) { Destroy(gameObject); }
?
cause the On$$anonymous$$ouseDown i dont know what it means:P
Answer by SkandYxyz · Jan 07, 2021 at 12:50 PM
Hi,
You can use this code in the objects update method:
public class DestroyPlayAudio : MonoBehaviour
{
public AudioSource audioSource;
public AudioClip clip;
public float volume=0.5f;
void Update()
{
if (Input.GetButtonDown ("0"))
{
Raycast ray=Camera.main.ScreenPointToRay(Input.mousePosition);
Raycasthit hit;
if (Physics.Raycast(ray, out hit))
{
Destroy(hit.collider.gameObject);
audioSource.PlayOneShot(clip, volume);
}
}
}
}
Insert your audiofile in the variable slot in the Monobehaviour.
If you want to create games fast without coding learn and use Playmaker or Game Creator.
Your answer
![](https://koobas.hobune.stream/wayback/20220613114455im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to rotate object on mouse click? 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Rotating a Sphere with the mouse? 1 Answer
Faux Gravity Prolem? #2 2 Answers