- Home /
How to destroy an object using Raycast or OnMouseButtonDown ?
Hi, I would like the child objects to be destroyed when I click on them. But for now, I just want to display the name but my script doesn't work at all I don't know why. Here's my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EachObjects : MonoBehaviour
{
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000f))
{
if (hit.transform != null)
{
PrintName(hit.transform.gameObject);
}
}
}
}
private void PrintName(GameObject go)
{
print(go.name);
}
}
Thx for your answers.
Works fine for me. Do you have a collider on your objects?
Answer by manaslegodesigns · Dec 05, 2017 at 04:28 PM
First get the gameobject public gameobject toDestroy;
To destroy objects i am using Destroy(toDestroy);
Tell me if this worked
I used void On$$anonymous$$ouseDown to destruct my objects to solve the problem =)
Answer by mbilalbark · Dec 06, 2017 at 02:34 PM
- Maybe you shall use OnPointerDown" method because very easy and very
perfect working.If you use OnPointerDown method has any rules.
Rules
This is true working for attached Game Object will have a collider.
This game main camera will have a Physics 2D Raycaster script component.
This must have script implement IPointerHandler interface class.
public class SampleClick: MonoBehaviour, IPointerDownHandler { public void OnPointerDown(PointerEventData eventData){ Debug.Log("Clicked"); } }
Your answer
Follow this Question
Related Questions
Problem with anims when attacking 1 Answer
Arial camera get selected point 2 Answers
Pick up paper view as gui 1 Answer
Mouse plane does not detect height 1 Answer
Button click moves GameObject to specific position 3 Answers