2015-02-03 1 views
0

나는 들어오는 소행성을 촬영하는 우주 게임을 만들고있다. 이 소행성은 동시에 일정량의 적을 생성 할 수있는 C# 스크립트로 생성됩니다. 스폰 위치는 2 개의 int 숫자 사이의 x 값에 대해 무작위이지만 현재 스크립트에서는 일부 적들이 서로 스폰하고 서로 다른 위치에서 각각의 적을 스폰 할 수있는 방법을 알 수 없습니다. 여기 내 시도, 어떤 도움을 주시면 감사하겠습니다.무작위로 있지만 다른 위치에있는 다수의 적을 산란하기

public int spawnCount; //number of asteroids that are spawned 
public Vector3 location; 
public GameObject asteroid; 
for (int i = 0; i < spawnCount; i++) 
    { 
     int locationGiver = 0; 
     int[] ChosenLocations = new int[]; 
      //Create an array to store previous chosen locations 
       int RandomLocation = Random.Range (-6, 6); 
       for(int l = 0; l < ChosenLocations.Length ;l++) 
       { 
      //Check if RandomLocation is not the same as any previously determined  locations 
        if(ChosenLocations[l] == RandomLocation) 
        { 
         RandomLocation = Random.Range (-6, 6); 
         l = 0; 
       //if it is the same, choose a new location and check if that one is different 
        } 
       } 
       location = new Vector3(RandomLocation, 0, 17); 
    //use the generated x value to create a location 
       Quaternion spawnRotation = Quaternion.identity; 
    //gives a random rotation to the asteroids, can be ignored 
       Instantiate (asteroid, location, spawnRotation); 
    //spawns the asteroid at the determined location 
       ChosenLocations[locationGiver] = RandomLocation; 
       locationGiver++; 
    //save the x-value in the array 
} 

답변

0

우선 ChosenLocations 배열의 크기를 지정해야합니다. 작성된대로 배열을 초기화하는 줄은 컴파일되지 않습니다. 크기가 동적 인 경우, 목록과 같은 다른 유형을 사용해야합니다.

문제 해결을 위해서

, 이제 배열이 같은 시도 크기 10

이다 가정하자 :

int[] ChosenLocations = new int[10]; 
bool match; 
Random r = new Random(); //I am using the .NET random generator, since I don't have Unity3d 
for (int l = 0; l < ChosenLocations.Length; l++) 
{ 
    match = true; 
    while (match) 
    { 
     int RandomLocation = r.Next(-6, 7);  
     if (!ChosenLocations.Contains(RandomLocation)) 
     { 
      match = false; 
      ChosenLocations[l] = RandomLocation; 
      // Instantiate your asteroids here... 
      Console.WriteLine(String.Format("Location {0}: {1}", l, ChosenLocations[l])); 
     } 
    } 
} 
Console.ReadKey(); 
+0

어이, 나는 당신과 내 코드를 대체하지만 지금은 통일이 완전하게 정지 첫 번째 스폰에 도착하자마자. 모든 것을 그대로 남겼습니다. (무질서 생성기를 사용하고 있기 때문에 .net 랜덤 생성기를 제외하고) 객체를 생성하는 코드를 추가했습니다. – kyllion001

+0

나는 화합에 대해 아무것도 모른다. 난 단지 반복하지 않고 임의의 숫자를 선택하는 방법에 대한 논리 문제를 해결하려고 노력했습니다. 화합에 관해 다른 질문을해야 할 수도 있습니다. 그러나 코드를주의 깊게 살펴보면 while 루프 내부 나 ChosenLocations 배열의 각 유닛을 순환하는 별도의 foreach 루프에서 생성 할 부분 중 하나가 필요하다는 것을 알 수 있습니다. 나는 코드의 산란 부분을 재구성하지 않았다. 그것은 당신에게 달려 있습니다. 코드를 디버깅하여 산란시 정확히 어떤 일이 일어나는지 확인하십시오. –

+0

또 다른 가능성은 (당신이 단결을 말했기 때문에) 당신은 끝없이 while 회 돌이에 갇혀 있다는 것입니다. 소행성의 최대 수가 가능한 위치의 수보다 클 경우에 발생합니다. –

관련 문제