Need help with specifics in Random.Range
Hello so I'm working on a project and I need help with coding a mini game where the player picks out of a 3x3 grid and winning something.
The premise is that the 3x3 grid takes a bet from the player and gives out a predetermined amount for them to win. As they pick from the 3x3 grid they win random amounts between the minimum of 0.05 and the total amount they won when they first made the bet. However the specifics I need help coding is that the win amounts should be no less than 0.05 increments(which is the minimum of my random.range) and they should always end in a 5 or 0.
I don't know how I can get that random number to only end in 5 or 0, that's where my hang up currently is. Does anyone know how to get this to work in c#? I'd be much grateful for any help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class TreasureController : MonoBehaviour
{
//List to control the Treasure Chests
public List<GameObject> treasureList = new List<GameObject>();
//Grabbing Other Scripts
public GameController gC;
public PlayButton pB;
//Floats
public float playerWinnings;
public float subtractTreasure;
public float chestPicker;
// Start is called before the first frame update
void Start()
{
//Making a list of gameobjects to control the treasures
foreach (GameObject Treasure in GameObject.FindGameObjectsWithTag("Treasure"))
{
treasureList.Add(Treasure);
}
foreach (GameObject Treasure in treasureList)
{
Treasure.SetActive(false);
}
}
// Update is called once per frame
void Update()
{
}
//Creates the 3x3 Grid when the player hits the button
public void CreateGrid()
{
chestPicker = Random.Range(1, 9);
foreach (GameObject Treasure in treasureList)
{
Treasure.SetActive(true);
}
}
//Destroys the grid when the player can't get win anymore
public void DestroyGrid()
{
chestPicker = 0;
foreach (GameObject Treasure in treasureList)
{
Treasure.SetActive(false);
pB.isPlaying = false;
}
}
//Generates a random number for picking a treasure
public void TakeMoney()
{
if(playerWinnings > 0.25f && chestPicker > 0.0f)
{
subtractTreasure = Random.Range(0.25f, playerWinnings);
playerWinnings -= subtractTreasure;
chestPicker -= 1;
}
else if (playerWinnings <= 0.25f || chestPicker == 0.0f)
{
subtractTreasure = playerWinnings;
playerWinnings -= subtractTreasure;
DestroyGrid();
}
}
Answer by Owen-Reynolds · Oct 15, 2020 at 06:18 PM
Say you want 0.05 to 2 by 0.05's. That's 40 values. The best way to make 40 values is rolling a random int. In this case roll 1 to 40 and convert:
float f = Random.Range(1,40+1)*0.05f;
If you wanted it to go from 3.0 to 5.0 by 0.05:
Random.Range (0,40+1)*0.05f+3 // or:
Random.Range(60,100+1)*0.5f
You way want to hand-check the low and high to see they match-up. It's easy to be off-by-1.