2017-06-13 23 views
0

其實我使用下面的代碼來檢測鼠標和某個對象之間的碰撞。獲取跨鼠標線的多個gameobjects的列表

我想要代碼捕獲多個GameObjects(不僅是第一個,但上面的那些)並將其存儲在列表中。我看了,但我有點困惑。

void Update() 
{ 
    RaycastHit hit; 

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 

    if(Physics.Raycast(ray,out hit)) 
    {  
     if (hit.collider != null) 
     { 
      print (hit.transform.gameObject.name);   

     }    
    } 
} 
+0

什麼讓RaycastAll困惑?文檔中甚至還有一個例子。 – Lestat

回答

3

這裏沒有什麼讓人困惑的。唯一的區別是,Physics.Raycast返回truefalse如果遇到什麼,而Physics.RaycastAll返回RaycastHit的數組。你只需要遍歷該數組RaycastHit

void Update() 
{ 
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 

    RaycastHit[] hit = Physics.RaycastAll(ray); 

    for (int i = 0; i < hit.Length; i++) 
    { 
     if (hit[i].collider != null) 
     { 
      print(hit[i].transform.gameObject.name); 
     } 
    } 
} 

注意

這是更好地使用Physics.RaycastNonAlloc,而不是Physics.RaycastAll如果要檢測每個對象命中。這不會分配內存,尤其是在Update函數中執行此操作時。

//Detect only 10. Can be changed to anything 
RaycastHit[] results = new RaycastHit[10]; 

void Update() 
{ 
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 

    int hitCount = Physics.RaycastNonAlloc(ray, results); 

    for (int i = 0; i < hitCount; i++) 
    { 
     if (results[i].collider != null) 
     { 
      print(results[i].transform.gameObject.name); 
     } 
    } 
} 

上面的代碼將檢測到最多10個對象。如果你願意,你可以增加它。

+0

感謝您的回答,您的意思是不用分配內存的方式? – JamesB

+1

當您的應用程序從操作系統請求內存塊時。你每幀都在做。這就像在更新函數中使用創建類的新實例,但這是一個數組。通過在函數之外聲明數組並重復使用它,使用'Physics.RaycastNonAlloc'函數,每次都不再是分配內存。因此,該功能中的'NonAlloc'關鍵字。來自C++,那就是我們所說的。不確定它是否與C#相同。爲每個幀分配內存可能會導致GC更頻繁地發生。這會暫時凍結遊戲並破壞遊戲體驗。 – Programmer

+1

谷歌「C#GC」,如果你不知道GC是什麼。如果你仍然困惑,你仍然可以搜索「C#stack vs heap」。這可能會幫助你。 – Programmer