拾荒者2D小游戏——敌人和食物的生成(数量和关卡有关)

GameManager物体上脚本我们再新增一个GameManager,一开始的MapManager因为一开始要生成的东西太多,因此我们为物体的生成单独用一个脚本,在关卡环节我们就要写GameManager中,在其中写public int level=1;因为这两个脚本位于同一个游戏物体里面,因此我们再mapManager中可以直接获取到GameManager中的level变量
private GameManager gameManager;
在Awake方法中获取一下
gameManager=GetComponent《GameManager》();
//创建食物 2——level2
int foodCount=Random.Range(2,gameManager.level
2+1);
for(int i=0;i<foodCount;i++)
{
Vector2 pos=RandomPosition();
GameObject foodPrefab=RandomPrefab(foodArray);
}
//创建敌人 固定level/2
int enemyCount=gameManager.level/2;
for(int i=0;i<enemyCount;i++)
{
Vector2 pos=RandomPosition();
GameObject enemyPrefab=RandomPrefab(enemyArray);
}

因为不管是生成食物还是敌人,我们都需要随机取得位置和随机取得游戏物体这两个步骤,因此我们可以将这两个设为两个专业方法,再用的时候可以直接调用
//1.随机取得位置
private Vector2 RandomPosition()
{
int positionIndex=Random.Range(0,positionList.Count);
Vector2 pos=positionList[positionIndex];
positionList.RemoveAt(positionIndex);
return pos;
}
//2.随机取得游戏物品(传递过来一个数组随机选择其中一个)
private GameObject RandomPrefab(GameObject[] prefabs)
{
int index=Random.Range(0,prefabs.length);
return prefabs[index];
}

猜你喜欢

转载自blog.csdn.net/vickieyy/article/details/82977197