Start and Stop with key input?
Hey Guys, what I'm trying to do here is create a very simple Lottery Simulator but, I'm stuck at getting the Update function to stop (not Pause) or stop when I reached the winning number. Any idea how I can get this working? I 'THINK' this needs to be a Coroutine but I'm just not sure which approach to take. Thanks!
What I have working:
Start displaying random numbers in GUI when the 'SPACE' key is pressed.
What I'm trying to figure out:
Stop the routine when the Winning int is found. OR...
Stop the routine when the 'SPACE' key is pressed a second time.
Slow down the update so it displays the numbers at are more readable pace( I know its deltaTime, just now positive how to implement it).
public bool gameIsRunning = false; public Text Lottery; public int winNumber = 1; private int printRange; void Update() { StartupKey (); if (gameIsRunning) { Lottery.text = "NUMBERS: " + Random.Range (1, 100).ToString (); } } void StartupKey() { if (Input.GetKeyDown (KeyCode.Space)) { gameIsRunning = true; }
Answer by SpaceManDan · Aug 29, 2015 at 05:59 AM
Try this out? Should work just the way you asked.
public bool gameIsRunning = false;
public bool youWon = false;
public Text Lottery;
public int winNumber = 1;
public int spinNumber;
private int printRange;
private float timerTime = 0.5f; //how long to wait until next roll. Currently set to 0.5 seconds.
private float timerNextTime;
void Update()
{
StartupKey();
if (gameIsRunning)
{
if (youWon == false)
{
if (timerNextTime <= Time.time)
{
spinNumber = Random.Range(1, 100);
Lottery.text = "NUMBERS: " + spinNumber;
timerNextTime = Time.time + timerTime; //add timerTime to Time to make it wait until the next timer to check and show a score.
}
if (spinNumber == winNumber)
{
youWon = true;
}
}
if (youWon)
{
Lottery.text = "YOU WIN!!!";
}
}
}
void StartupKey()
{
if (Input.GetKeyDown(KeyCode.Space) && gameIsRunning == false)
{
gameIsRunning = true;
}
else if (Input.GetKeyDown(KeyCode.Space) && gameIsRunning == true)
{
gameIsRunning = false;
}
}
Oh yeah, slowing it down.
add the code Time.timeScale = 0.5f;
1 is full speed. 0.5 is half speed... and so on.
O$$anonymous$$ never$$anonymous$$d about my timescale comment. It isn't helping. You will need to implement a Timer. Give me a second I'll help you out.
Ok, there. I edited the code to add a timer into it. That should do all the stuff you needed it to. You were on the right track. You just needed a few booleans to keep track of what state things are in. True or False is a switch. on and off. Very powerful in the right hands.
Answer by dead_byte_dawn · Sep 01, 2015 at 08:07 PM
Thanks @SpaceManDan! I'll be checking your code out asap.
Your answer
