在unity中做一个70%的几率生成十个怪物或30%的概率生成10个黏土或15个木材的代码
时间: 2024-03-02 10:54:03 浏览: 153
基于Unity的小游戏代码
5星 · 资源好评率100%
以下是在Unity中生成怪物、黏土和木材的代码,生成的数量随机,但总数为10个怪物或15个黏土或木材,其中70%为怪物,30%为黏土或木材:
```csharp
int totalObjects = 25;
float rand = Random.value;
if (rand < 0.7f) // 生成怪物
{
int numCreatures = Mathf.RoundToInt(totalObjects * 0.7f);
int numResources = totalObjects - numCreatures;
for (int i = 0; i < numCreatures; i++)
{
GameObject creature = Instantiate(creaturePrefab, spawnPoint.position, Quaternion.identity);
}
for (int i = 0; i < numResources; i++)
{
float subRand = Random.value;
if (subRand < 0.5f)
{
GameObject clay = Instantiate(clayPrefab, spawnPoint.position, Quaternion.identity);
}
else
{
for (int j = 0; j < 3; j++)
{
GameObject wood = Instantiate(woodPrefab, spawnPoint.position, Quaternion.identity);
}
}
}
}
else // 生成黏土或木材
{
int numResources = Mathf.RoundToInt(totalObjects * 0.3f);
for (int i = 0; i < numResources; i++)
{
float subRand = Random.value;
if (subRand < 0.5f)
{
GameObject clay = Instantiate(clayPrefab, spawnPoint.position, Quaternion.identity);
}
else
{
for (int j = 0; j < 3; j++)
{
GameObject wood = Instantiate(woodPrefab, spawnPoint.position, Quaternion.identity);
}
}
}
}
```
这段代码会根据设定生成总共25个对象,其中70%(即10个)为怪物,30%(即15个)为黏土或木材。注意,生成的是10个怪物或15个黏土或木材,不会同时生成。其中,黏土和木材的生成概率分别为15%。注意,spawnPoint是一个变量,需要在代码中定义。
阅读全文