Hello! I want to figure out how I can slow down the while loops. If you don’t understand what I am talking about (which you most likely don’t) I have a hunger variable. When that variable reaches 0, I want the health to go down at a constant speed. (For ex. 1 health decrease per second) If I regularly use the while loops, the health immediately goes down to 0. How would I make the while loops go down at a constant speed?
script for more info:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class money : MonoBehaviour {
public int currentMoney = 100;
public int currentApple = 0;
public int hunger = 100;
public int health = 100;
void Start () {
}
void Update () {
if (Input.GetKeyDown (KeyCode.B)) {
SceneManager.LoadScene ("shop");
DontDestroyOnLoad (transform.gameObject);
}
}
void OnGUI() {
GUI.Label(new Rect(25,400,Screen.width, Screen.height), "$" + currentMoney);
}
void BuyApple() {
if (currentMoney >= 20) {
currentApple += 1;
}
}
void food() {
if (hunger == 0) {
//Here is where I want to put the while loop
}
}
}
// inside the class...
private int health = 10;
private int hunger;
void Start () {
StartCoroutine(UpdateHealth());
}
private IEnumerator UpdateHealth() {
while (health > 0) {
yield return new WaitForSeconds(1);
if (hunger == 0) {
health--;
}
}
// here do something where player dies of hunger :(
}
Thanks for the answer, @LiloE! Previously, your answer has worked for me but I cannot use it for my new game.
Here is the script that I have used:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class hungerchange : MonoBehaviour {
public int hunger = 100;
public int health = 100;
void Start () {
StartCoroutine (UpdateHealth ());
}
private IEnumerator UpdateHealth() {
while (health > 0) {
yield return new WaitForSeconds (1);
if (hunger == 0) {
health--;
}
}
if (health == 0) {
//SceneManager.LoadScene("Scene");
}
}
public void OnGUI() {
GUI.Label (new Rect(0, 0, Screen.width, Screen.height), "Health: " + health + "/100");
GUI.Label (new Rect(0, 20, Screen.width, Screen.height), "Hunger: " + hunger + "/100");
}
}
It justs stays on 100/100 for hunger and doesn’t decrease. Please help!