- Home /
Decrease a value during a certain amount of time based on another value
hello everyone,
So I have this value:
public int gold = 400;
That is located on another script.
I want, first of all, to get access to this value, which is not complicated. My problem is mostly that I need to do a function that will repair the hp of an object (a repair function) based on this value.
It will increment hp by 1 by frame (or more) up to full hp. But each "digit" restored must cost something, so I need to decrease the value of gold as long as this function is active.
I have no clue how to do that. I've been working on this for the last hours... Any suggestions? :S
NOTE : I code in c#.
Answer by Berenger · Apr 25, 2012 at 06:28 PM
For anything over time, think Update or coroutines. Each occurence of the event "I give 1 hp, but gimme the money mate !" you need to 1) check if there is enough gold 2) increase hp 3) deacrease the gold. It's probably going to look like that :
private WhoeverHaveGold guy;
private void Awake()
{
guy = ...
}
public void StartRepair(){ StartCoroutine( Repair() ); }
private IEnumerator Repair()
{
while( hp < hpMax && guy.gold > hpCost ) // 1)
{
hp++; // 2)
guy.gold -= hpCost; // 3)
yield return null; // Wait one next frame
//yield return new WaitForSeconds( repairFreq ); //Wait x seconds
}
print( "Repair of " + name + " by " + guy.name + " done." +
"\nHp : " + hp + "/" + hpMax." + " Gold : " + guy.gold + "." );
}
Interesting, I'll try this. Also, is there a way to stop the coroutine, or this code, in any way other than to wait for the while to reach its end? (ex: user press a key, or click on a particular button)
you can get out with if(Input.Get$$anonymous$$eyDown(Choose a button))break;
But the Coroutine will work nonetheless... that's what I heard / read...
There is three ways to stop a coroutine, that I can think of at least :
Let Unity do the work. If it was call with a string, you can use StopCoroutine.
By reaching the end of the function. You can have an extra boolean in the while(...), once set to false it will leave the loop at the next iteration. A break; would do as well.
By using yield break, which stop the coroutine right away, when the line is executed.