unity3d - Decreasing a float after a set amount of time -
this little difficult explain want write piece of code decreases users oxygen level after set amount of time. example, if user swimming users oxygen level should go down .5 every 5 seconds. have general idea can not seem figure out how write code. here have far
c#
public float timer = 60; public float oxygen = 100; public float decreaseoxygen = 0.5f; public float oxygendecreaseinterval = 2; private float decreaseoxyovertime(float amounttodecrease) { oxygen = oxygen - amounttodecrease; return oxygen; } private float createdelaytimer() { float delayedtime = timer - oxygendecreaseinterval; invokerepeating("delayedtime", 0, 5f); return delayedtime; } void update() { if (timer >= createdelaytimer()) { oxtext.text = "oxygen: " + decreaseoxyovertime(decreaseoxygen) + "%"; } timer -= time.deltatime; }
why not use coroutine
?
when want start decrease in oxygen can this:
startcoroutine("decreaseovertime", amounttodecreaseby, interval); ienumerator decreaseovertime(float amounttodecreaseby, float interval) { float adjust = 0; while(true) { var prev = datetime.now; yield return new waitforseconds(interval-adjust); adjust = datetime.now.subtract( prev ).seconds - interval; } }
i'm assuming interval
measured in seconds.
note: i'm calling startcoroutine
using it's name instead of calling method can stop later stopcoroutine
.
Comments
Post a Comment