Unity c# 用鼠标单击销毁生成的预制件

Unity c# destroy spawned prefab with mouse click

我有一个脚本可以在游戏中的随机位置生成猫,当用户点击它们时它们应该被销毁。但是,我的脚本遇到了问题,想知道是否有人知道光线投射出了什么问题?

public void CatClick () {
            if (Input.GetMouseButtonDown (0)) {
                Ray = Camera.main.ScreenPointToRay (Input.mousePosition);

                if (Physics.Raycast(Ray, out RaycastHit)) {

                    Destroy(RaycastHit.collider.gameObject);
            }
        }

    }

你不应该签入更新功能吗?

就像 Arne 说的,确保你在更新功能中检查它,如果它是一个 2d collider,确保你将它更改为

 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
       }
 }

另一种方法

 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);
    }
 }

把这个脚本放在"cat"预制件上,如果你点击它,它会破坏"cat"。

你必须像这样放置你的代码来更新函数:

 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
     }
   }
 }