随机物品掉落

时间:2018-01-18 07:12:37

标签: c# unity3d

我正在开发一款安卓游戏,当敌人死亡时,它会使用下面的代码将地面上的物品丢弃。该代码适用于单个项目,但如何对代码进行适当的更改,以便从数组中删除随机项目。

public GameObject dropitems; 
float droprate = 0.25f;

public void DropItem()
{
    if(Random.Range(0f,1f)<=droprate)
        Instantiate (dropitems, this.transform.position, this.transform.rotation);
}

1 个答案:

答案 0 :(得分:2)

您需要将dropitems更改为GameObject数组。您可以在编辑器屏幕上将其填充为列表。此外,当程序流达到项目丢弃的状态时,您需要定义另一个随机数。索引应该介于0和dropItems中的项目数之间。

public GameObject[] dropitems; 
float droprate = 0.25f;

public void DropItem()
{
    if(Random.Range(0f,1f)<=droprate)
    {
        int indexToDrop = Random.Range(0, dropItems.Length);
        Instantiate (dropitems[indexToDrop], this.transform.position, this.transform.rotation);
    }
}

请注意,当您使用带有Random函数的Random.Range(int min, int max)时,它会返回min [inclusive]和max [exclusive]之间的整数,as it is stated in the documentation

相关问题