在随机但不同的位置产生一些敌人

时间:2015-02-03 21:53:07

标签: c# unity3d

我正在制作太空游戏,你可以在那里射入小行星。这些小行星是用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
}

1 个答案:

答案 0 :(得分: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();