2017-02-21 7 views
0

私はゲーム内のランダムな位置に猫をスポーンするためのスクリプトを用意しています。私はスクリプトに問題がありますが、誰かがレイキャストに何が間違っているか分かっているのだろうかと疑問に思っていましたか?Unity c#はマウスクリックで生成されたプレハブを破棄します

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

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

        Destroy(RaycastHit.collider.gameObject); 
      } 
     } 

    } 

答えて

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

更新機能をチェックしないでください。

0

アルネは、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 
     } 
} 
関連する問題