- Home /
Help with waiting / coroutine c#
I am extremely new to C# and scripting in general. I need help making this do
curHealth = (curHealth - 1)
, or decrease curHealth by 1, every 9 seconds. I have looked into coroutines, but I do not fully understand them.
Here is my script:
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLength;
void Start () {
healthBarLength = Screen.width / 1;
}
void Update () {
AdjustCurrentHealth (0);
}
void OnGUI() {
GUI.Box (new Rect (4, 4, healthBarLength, 8), curHealth + "/" + maxHealth);
}
public void AdjustCurrentHealth(int adj) {
curHealth += adj;
if(curHealth < 0)
curHealth = 0;
if(curHealth > maxHealth)
curHealth = maxHealth;
if (maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width / 1) * (curHealth / (float)maxHealth);
}
}
Thank you for your time and any help.
Answer by rutter · Dec 03, 2013 at 02:12 AM
There are some simple examples at the coroutines manual page.
Something like this could work:
void Start() {
StartCoroutine(HealthLoop(9f));
}
IEnumerator HealthLoop(float delay) {
while (true) {
curHealth -= 1;
yield return new WaitForSeconds(delay);
}
}
There's a lot of reading you can do with coroutines, but at the most basic level they're just a function with some yield statements. Each time you yield, it waits. You can yield on many things, like a level loading, a WWW call returning, some amount of time passing, or even another frame rendering.
The only confusing thing is that your function will execute over multiple frames. You're probably not used to that.
Or, if you'd like to go even simpler and use InvokeRepeating:
void Start() {
InvokeRepeating("HealthDrop", 9f, 9f);
}
void HealthDrop() {
curHealth -= 1;
}
Your answer
Follow this Question
Related Questions
Wait inside method until user action 3 Answers
C# Coroutine help 1 Answer
A simple Wait-Function without Coroutine (C#) 12 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers