1. 动态创建预制体
cs
// 在外部拖入预制体
public GameObject enemy;
void Start()
{
for (int i = 0; i < 5; i++)
{
// 生成游戏对象:Instantiate();
GameObject ENEMY = Instantiate(enemy);
// 根据i的增大,一字排开
ENEMY.GetComponent<Transform>().Translate(i * 1f, 0, 0);
}
}
2. 随机动态生成预制体
cs
// 在外部拖入预制体
public GameObject enemy;
void Update()
{
// 创建三个坐标轴的随机数
float x = Random.Range(-50, 50);
float y = Random.Range(-50, 50);
float z = Random.Range(-50, 50);
GameObject ENEMY = Instantiate(enemy);
ENEMY.GetComponent<Transform>().Translate(x,y,z);
}
3. 控制生成速度
cs
// 在外部拖入预制体
public GameObject enemy;
// 允许小球存在的个数
public int total;
// 计时器
int num;
// 当前创建第几个小球
int currentTotal = 0;
void Update()
{
// 创建三个坐标轴的随机数
float x = Random.Range(-50, 50);
float y = Random.Range(-50, 50);
float z = Random.Range(-50, 50);
// 计算每10帧生成一次
if (num % 10 == 0)
{
GameObject ENEMY = Instantiate(enemy);
ENEMY.name = "qiu" + currentTotal;
currentTotal++;
ENEMY.GetComponent<Transform>().Translate(x, y, z);
// 如果 当前总数 超过 允许存在的总数
if (currentTotal >= total)
{
GameObject desObj = GameObject.Find("qiu" + (currentTotal - total));
// Destroy() 销毁游戏对象
Destroy(desObj);
}
}
num++;
}
4. 控制生成总数
cs
// 在外部拖入预制体
public GameObject enemy;
// 允许小球存在的个数
public int total;
// 计时器
int num;
// 当前创建第几个小球
int currentTotal = 0;
void Update()
{
// 创建三个坐标轴的随机数
float x = Random.Range(-50, 50);
float y = Random.Range(-50, 50);
float z = Random.Range(-50, 50);
// 计算每10帧生成一次
if (num % 10 == 0)
{
GameObject ENEMY = Instantiate(enemy);
ENEMY.name = "qiu" + currentTotal;
currentTotal++;
ENEMY.GetComponent<Transform>().Translate(x, y, z);
// 如果 当前总数 超过 允许存在的总数
if (currentTotal >= total)
{
GameObject desObj = GameObject.Find("qiu" + (currentTotal - total));
// Destroy() 销毁游戏对象
Destroy(desObj);
}
}
num++;
}