How to destroy a game object using Raycast in Unity
Notes:
How to destroy a game object using Ray cast on Mouse Click in Unity 3D:
Example Code:
using UnityEngine;
public class ObjectDestroyer : MonoBehaviour {
void Update () {
// 1. Test for mouse click
if (Input.GetMouseButtonUp (0)) {
// 2. get mouse position in world space
Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 100f));
//3. get direction vector from camera position to mouse position in world space
Vector3 direction = worldMousePosition - Camera.main.transform.position;
RaycastHit hit;
//4. cast a ray from the camera in the given direction
if (Physics.Raycast (Camera.main.transform.position, direction, out hit, 100f)) {
Debug.DrawLine (Camera.main.transform.position, hit.point, Color.green, 0.5f);
// 5. Destroy game object
if (hit.collider.gameObject.tag == "Enemy") {
Destroy (hit.collider.gameObject);
}
} else {
Debug.DrawLine (Camera.main.transform.position, worldMousePosition, Color.red, 0.5f);
}
}
}
}