2017-02-21 55 views
0

我有一個腳本在遊戲中隨機位置產生貓,當用戶點擊它們時,它們應該被銷燬。然而,我的腳本遇到了麻煩,並且想知道是否有人知道raycast出了什麼問題?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); 
    } 
} 

把這個腳本放在「貓」預製件上,如果你點擊它,它會摧毀「貓」。

或者必須把你這樣的代碼更新功能:

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