2017-08-13 34 views
-2

這裏是相關的代碼。我想檢查當前的產卵位置是否在最後一個產卵陣列中。如何檢查矢量3是否在矢量3數組中c#

lastSpawnsVector3的數組。

//Generate Level 
while(cubeSpawns != 100) 
{ 
    currentSpawnLocation = new Vector3(Random.Range(-5, 5), Random.Range(-5, 5), Random.Range(-5, 5)); 
    if (currentSpawnLocation != lastSpawns) 
    { 
     GameObject cubeClone = (GameObject)Instantiate(Cubes[Random.Range(0,Cubes.Length)], transform.position + currentSpawnLocation, Quaternion.identity); 
     currentSpawnLocation = lastSpawns[cubeSpawns]; 
     cubeClone.transform.parent = CubeClones; 
     cubeSpawns = cubeSpawns + 1; 
    } 
} 
+3

此代碼甚至不會編譯。你甚至試過研究這個(例如:在搜索引擎中輸入「C#array contains」)? – UnholySheep

回答

1

您可以使用靜態IndexOf超負荷本地Array類。它將返回您在數組中找到對象的位置,如果對象不存在於數組中,則返回-1。

所以,你的代碼應該是這樣的(你不需要while循環了):

currentSpawnLocation = new Vector3(Random.Range(-5, 5), Random.Range(-5, 5), Random.Range(-5, 5)); 
if (Array.IndexOf(lastSpawns, currentSpawnLocation) == -1) 
{ 
    // the currentSpawnlocation is not found 
    GameObject cubeClone = (GameObject)Instantiate(Cubes[Random.Range(0,Cubes.Length)], transform.position + currentSpawnLocation, Quaternion.identity); 
    cubeClone.transform.parent = CubeClones; 
    // I assume you want to store currentSpawnLocation in the array 
    // for that I use your cubeSpawns variable to keep track of where 
    // we are in the array. If you use cubeSpawns for something else, adapt accordingly 
    lastSpawns[cubeSpawns] = currentSpawnLocation; 
    cubeSpawns = cubeSpawns + 1; 
    // prevent going beyond the capacity of the array 
    // you might want to move this in front of the array assingment 
    if (cubeSpawns > lastSpawns.Length) 
    { 
     // doing this will overwrite earlier Vector3 
     // in your array 
     cubeSpawns = 0; 
    } 
} 
+0

非常感謝! – lukefly2