Reputation: 1683
I have a script to spawn cats at random positions in the game and when the user clicks on them they should be destroyed. I am having trouble with my script however and was wondering if anyone knew what was wrong with the raycast?
public void CatClick () {
if (Input.GetMouseButtonDown (0)) {
Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast(Ray, out RaycastHit)) {
Destroy(RaycastHit.collider.gameObject);
}
}
}
Upvotes: 0
Views: 1275
Reputation:
Another way to do it:
using UnityEngine;
using System.Collections;
public class CatDestructor : MonoBehaviour
{
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
void OnMouseDown()
{
// Destroy game object
Destroy (this.gameObject);
}
}
Put this script on "cat" prefab and if you click on it, it will destroy the "cat".
Or you must put your code to update function like this:
void Update(){
if (Input.GetMouseButtonDown(0)){ // if left button pressed...
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)){
// the object identified by hit.transform was clicked
// do whatever you want
}
}
}
Upvotes: 1
Reputation: 568
like Arne said, make sure you check it in the update function, also if it's a 2d collider make sure you change it to
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.GetRayIntersection(ray, Mathf.Infinity);
if (hit.collider != null)
{
// do whatever you want to do here
}
}
Upvotes: 1