- Home /
Simple Way to Remove a Single Object on Click/Touch
This is, I'm certain, an incredibly dumb question. I've been trying to learn Unity, and have followed some tutorials to make some simple games like a Breakout Clone, etc.
I'm now trying to make a simple hidden object game, and I'm trying to write what should be the easiest script in the world – on tap/click I want the item that is tapped/clicked to be destroyed.
The problem is, the way I thought I would go about doing that isn't working:
void Update () {
if (Input.GetMouseButtonDown (0)) {
Destroy(gameObject);
}
}
When I attach this script to all of the items to be tappable/clickable, what happens is if I click any one of them, all of them vanish at once.
I would be very grateful if someone could help me with the simplest way to make it so only the object I click on disappears. I tried using 'this', but that seems to destroy the script (which makes sense), not the object itself.
Thank you so much!
I should note that this is 2D and in C#.
Answer by ForeignGod · Apr 03, 2015 at 12:28 AM
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void OnMouseDown() {
Destroy(gameObject);
}
}
This doesn't seem to be working, and I'm sure there's something I'm messing up.
I've created the script as a C# script, and added it to each of the objects I want to be clickable/touchable as a Component. But nothing seems to be happening.
I'm not sure what might be missing. I tried adding a $$anonymous$$inematic Rigidbody 2D to the items, thinking maybe that was the problem, but that doesn't seem to have fixed it. Is there something obvious I could be missing?
Thank you so much for your patience.
Never$$anonymous$$d, it was something I was messing up.
I didn't realize it needed to have a Collider on it.
Thank you so much for your help!
Answer by Dominic.Shea · Apr 03, 2015 at 03:46 AM
if(Input.GetMouseButtonDown(0))
{
Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
RaycastHit2D hit = Physics2D.Raycast(mousePos,Vector2.zero, 100f);
if(hit.collider != null)
{
Destroy(hit.collider);
}
}
Add this to your main camera, and make sure that the objects you are destroying have colliders on them.
What if you were to do the same with touch controls??
Your answer