Unity c#用鼠标点击破坏生成的预制件

时间:2017-02-21 20:01:29

标签: collision-detection unity5

我有一个脚本在游戏中的随机位置产生猫,当用户点击它们时,它们应该被销毁。然而,我的脚本有问题,并且想知道是否有人知道光线投影有什么问题?

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

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

                    Destroy(RaycastHit.collider.gameObject);
            }
        }

    }

3 个答案:

答案 0 :(得分:1)

你不应该检查更新功能吗?

答案 1 :(得分:1)

另一种方式

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

答案 2 :(得分:0)

像Arne说的那样,确保你在更新功能中检查它,如果它是2d对撞机,请确保将其更改为

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