- Home /
When click on object, then destroy
Hi everybody, I know that is this question so much times asked but i have a little problem.. I have a "Object" and i want to destroy it when i click on it.. I have a code:
if(didClick == true) {
Destroy (this.gameObject);
}
(Just a part of original code but this is only necessary) So this code works fine but this code do: When i click anywhere on the screen, my object will be destroyed. But i need code that will destroy object only when click on it. I have BoxColidier2D on that object. Please if anyone knows how to fix this? Thank you!
Use ray casting through the clicked point on the screen, and if that hits something, destroy it.
Answer by Addyarb · Sep 26, 2014 at 08:33 PM
Very very simple and yet elegant way:
Add a collider to your object (can set trigger if you need to pass through it).
void OnMouseDown()
{
Destroy(this.gameObject);
}
This function checks if the mouse pointer is over the object and if the mouse is down. A sort of built-in unity function that is very useful. Just remember you must have a collider, and it must not be inside another collider.
Thank you so much! :D I missed that "void On$$anonymous$$ouseDown()" it wasn't in my function! :D
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
Follow this Question
Related Questions
Selecting gameobjects in game, 3 Answers
Click to destroy object 2 Answers
How Do You Exit A Game 0 Answers
How to disable click to move on interface elements ? 0 Answers
Text popup onMouseDown 2 Answers