在unity中做一个50%的几率生成黏土,30%的概率生成木材,10%的概率生成羽毛,10%的概率生成珍珠,10%的概率生成宝石的代码
时间: 2024-03-03 18:47:44 浏览: 23
下面是在Unity中实现生成不同物品概率的代码:
```
public GameObject clayPrefab;
public GameObject woodPrefab;
public GameObject featherPrefab;
public GameObject pearlPrefab;
public GameObject gemPrefab;
public void GenerateItem()
{
float randomNumber = Random.Range(0f, 1f);
if (randomNumber <= 0.5f)
{
Instantiate(clayPrefab, transform.position, Quaternion.identity);
}
else if (randomNumber <= 0.8f)
{
Instantiate(woodPrefab, transform.position, Quaternion.identity);
}
else if (randomNumber <= 0.9f)
{
Instantiate(featherPrefab, transform.position, Quaternion.identity);
}
else if (randomNumber <= 0.95f)
{
Instantiate(pearlPrefab, transform.position, Quaternion.identity);
}
else
{
Instantiate(gemPrefab, transform.position, Quaternion.identity);
}
}
```
首先,我们定义了五个游戏对象变量,分别代表不同的物品预制体。然后,我们定义了一个名为GenerateItem的公共方法,用于生成不同的物品。在方法中,我们使用Random类的Range方法生成一个0到1之间(包括0和1)的随机浮点数。根据该随机数的大小,我们使用if-else if语句生成不同的物品。
当随机数小于或等于0.5时,生成黏土;当随机数大于0.5且小于或等于0.8时,生成木材;当随机数大于0.8且小于或等于0.9时,生成羽毛;当随机数大于0.9且小于或等于0.95时,生成珍珠;当随机数大于0.95时,生成宝石。
注意,这里的概率都是近似值,因为随机数的生成是伪随机的,而不是真正的随机。
相关推荐
![unitypackage](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)