- Home /

# Need some help with Random.value and Instantiating objects.

Need some help with Instantiating Coin objects when the enemy dies . Here I've a Top-Down space shooter game where enemies die and drop coins from the array of Coins where I've 4 different Coin prefabs Copper ,silver , gold and Super coin each with certain value. What i wanted to implement is a percent wise drop rate for each coin.

```
public void DropCoin() /// called when enemy dies.
{
for (float i = 0; i < GetNoOfCoinsChance() ; i++)
{
GameObject Coin = Instantiate(AllCoins[GetCoinType()], transform.position, transform.rotation) as GameObject;
Coin.GetComponent<Rigidbody2D>().AddForce(new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, -1.5f)), ForceMode2D.Impulse);
Debug.Log(GetCoinType());
}
}
public float GetNoOfCoinsChance() // No. of coins to spawn chance
{
if (Random.value <= 0.8) { return 1; }
if (Random.value <= 0.5) { return 2; }
if (Random.value <= 0.3) { return 3; }
if (Random.value <= 0.2) { return 4; }
if (Random.value <= 0.1) { return 5; }
else { return 0; }
}
public int GetCoinType() // Type of coin to spawn
{
if (Random.value <= 0.8) { return 0; }
if (Random.value <= 0.6) { return 1; }
if (Random.value <= 0.4) { return 2; }
if (Random.value <= 0.2) { return 3; }
else { return 0; }
}
```

Here the for loop describes the no. of coin chance to spawn when a enemy dies and GetCoinType() defines the type of coin to spawn , The GetNoOfCoinsChance() works perfectly, but for some reason the GetCoinType() doesn't work it just spawn the copper coin every time i.e AllCoins[0]; Please can someone help me out with this problem. Thanks in advance. :).

**Answer** by Hellium
·
Jun 11 at 02:53 PM

I don't know if the following will solve your problem, but there is a big problem with your `GetNoOfCoinsChance`

and `GetCoinType`

functions. You call `Random.value`

multiple times, generating a new random value each time.... And you should do your checks from the lowest chance to highest chance.

You should do the following:

```
public float GetNoOfCoinsChance() // No. of coins to spawn chance
{
float r = Random.value;
if (r <= 0.1f) { return 5; }
if (r <= 0.2f) { return 4; }
if (r <= 0.3f) { return 3; }
if (r <= 0.5f) { return 2; }
if (r <= 0.8f) { return 1; }
else { return 0; }
}
public int GetCoinType() // Type of coin to spawn
{
float r = Random.value;
if (r <= 0.2f) { return 3; }
if (r <= 0.4f) { return 2; }
if (r <= 0.6f) { return 1; }
else { return 0; }
}
```

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.