Hello guys, I’m newbie at Unity and C#, so if some my question is stupid, just excuse me. Also my english can be bad.
I need to change some value, for example Player MP over time. As I understand Coroutines are best way for this, but seems I can’t figure out right logic.
I have Player script that contain this function:
void Pee()
{
#if UNITY_STANDALONE
if (Input.GetMouseButtonDown(0) && IsGrounded() == true && inShop == false)
#elif UNITY_EDITOR
if (Input.GetMouseButtonDown(0) && IsGrounded() == true && inShop == false)
#elif UNITY_ANDROID
if (CrossPlatformInputManager.GetButtonDown("Pee") && IsGrounded() == true && inShop == false)
#endif
{
if (curMP > 0)
{
_playerAnim.Pee();
SetMP(1,0);
StartCoroutine(RestoreMP());
}
}
}
As you can see my Player can pee, don’t mind, player is a dog, so he should… But I use RPG-like vars names.
When Player pee he lost 1 MP point from 5 at all. I want he could restore 1 point each 5 seconds.
I write this
IEnumerator RestoreMP()
{
if (curMP < defMP)
{
canRestoreMP = false;
yield return new WaitForSeconds(5);
SetMP(1, 1);
Debug.Log("Timer set player MP to: " + curMP);
canRestoreMP = true;
}
}
It work fine, but also timer start after pee function, so if Player pee five times in second, MP restores five times in second. And in log I saw max value 4, not 5, but actually player has 5 MP.
When I tried put StartCoroutine(RestoreMP()) to Update function, it start a lot of timers each tick, and curMP < defMP just ignored (I don’t know why), I tried to use some bool variables to prevent this, but didn’t get any success. Help me please, I think it’s simple, just my head can’t find right way for this.
Also if someone ask about SetMP(), this is it, but I think that’s no matter.
public void SetMP(int amount, int type)
{
switch (type)
{
case 0: // Take MP from player
curMP -= amount;
break;
case 1: // Give MP to player
curMP += amount;
break;
}
UIManager.Instance.UpdateMPBar(curMP);
Debug.Log("Player::SetMP function set player MP to: " + curMP);
}