- Home /
Problems with C# Coroutines
I am kind of new to C# and am kind of confused about why my script wont work.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class JohnKing : MonoBehaviour {
private int HP;
private int ATK;
private int DEF;
private int SP;
private int Special;
public Vector2 startpos;
public Text HealthText;
void Start ()
{
HP = 100;
ATK = 10;
DEF = 5;
SP = 10;
Special = 30;
transform.position = startpos;
HealthText.text = HP.ToString ();
StartCoroutine ( "Health" );
}
void Update ()
{
}
IEnumerator Health (int HP)
{
yield return new WaitForSeconds (1f);
HP = HP - 1;
}
} `
change
IEnumerator Health (int HP)
to
IEnumerator Health ()
So you are decreasing the class's HP value, ins$$anonymous$$d of the functions local HP value.
Answer by Legend_Bacon · Mar 27, 2018 at 09:56 AM
Hello there,
From what I understand you want your character to lose 1 HP every second, right? In this case, what you need to do is this:
void Start ()
{
HP = 100;
ATK = 10;
DEF = 5;
SP = 10;
Special = 30;
transform.position = startpos;
HealthText.text = HP.ToString ();
StartCoroutine (Health() );
}
IEnumerator Health ()
{
while(HP > 0)
{
HP--;
HealthText.text = HP.ToString ();
yield return new WaitForSeconds (1.0f);
}
yield return null;
Debug.Log("Character is at 0 HP!");
}
If this is not what you meant to do, please let me know and I'll adjust the script. It's always better to tell people what you are trying to do when asking for help!
Hope that helps!
Cheers,
~LegendBacon
Thanks everyone, but now I have another problem, when a co-routine gets to its last line of code, does it go back to the start of the co-routune or just stops?
It just stops. Unless you are using a while loop.
Answer by Summit_Peak · Mar 27, 2018 at 01:13 AM
Instead of using: StartCoroutine ( "Health" ); Try: StartCoroutine(Health(HP));
Answer by mani3307 · Mar 27, 2018 at 07:05 AM
@Questrocker Just move "StartCoroutine ( "Health" );" from start() to Update() loop then it will work. This is because start only runs once through the lifetime of a script
Answer by Priyanka-Rajwanshi · Mar 27, 2018 at 08:36 AM
@Questrocker Since you are using a parametrised function, i.e. Health (int HP) with HP as parameter, you cannot call Coroutine with
StartCoroutine ( "Health" );
as you are not assigning value to the parameter.
Rather you should use:
StartCoroutine (Health( HP ));
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
StartCoroutine not working in Update!!! 0 Answers
Coroutine running twice 1 Answer