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!
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.
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.