I have game object here where inside that game object I have 2D sprite and I have this script attach to gameobject. But when I click the sprite it won’t destroy why ??, sorry for asking thi snewbie questio. I’m stilll new and learning this unity. Hope u guys can teach me
using UnityEngine;
using System.Collections;
public class TakePhoto : MonoBehaviour {
void OnMouseDown() {
Destroy(gameObject);
}
}
Click on the GameObject. Click on AddComponent. Type in collider or collider2d. Choose one as appropriate.
Note that OnMouseDown is an old method. Strictly speaking its not legacy. But you might want to consider using the EventSystem instead to make things nicer with your UI. You can always change it later, so no biggie.
The EventSystem works by gathering all of your inputs into one place first before sending them out to your various objects. I’m not sure if its objectively better. But it does make working with the UI easier as it will automatically prevent clicks from the UI system touching your in game system.
Ooh that’s mean we script all user input in 1 script to detect all the 2d sprite, button or something click. Not at different script where I make my script function on mouse down 1 by 1. Like that ??
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class TakePhoto : MonoBehaviour, IPointerClickHandler {
void OnClick() {
Destroy(gameObject);
}
}
You would also need an event system in the scene, an appropriate physicsraycaster on your camera, and an appropriate collider on your gameobject
oh wait2 so 1 I must UI > Eventsystem then I put the collider and physicraycaster in this event system or, I put my maincamera > physyc raycater and gameobject > sprite and collider in the event system ??
I get error message with IPointerClickHandler, when I write the code u give above. here is my properties, check it at jpg there. Am I doing it wrong ??
Bad idea these days. You want to implement the IPointerClick interface instead.
OnMouseDown is the old way of doing it. Its not compatible with the UI system, and will cause problems. Its only still included for backwards compatibility.