I put in a yield and the WaitForSeconds() as well, but it doesn’t work.
Here is the code:
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public Transform target;
public float healthBarLength;
// Use this for initialization
void Start () {
healthBarLength = Screen.width / 2;
animation["death"].wrapMode = WrapMode.Once;
animation["death"].layer = 1;
}
// Update is called once per frame
void Update () {
AddjustCurrentHealth(0);
}
void OnGUI() {
GUI.Box (new Rect(10, 40, healthBarLength, 20), curHealth + "/" + maxHealth);
}
public void AddjustCurrentHealth(int adj) {
curHealth += adj;
if(curHealth < 0)
curHealth = 0;
if(curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width / 2) * (curHealth / (float)maxHealth);
if(curHealth <= 0){
animation.Play ("death");
yield WaitForSeconds(3);
Application.LoadLevel(2);
}
}
}
Implement these changes and see if it helps: From your original
public void AddjustCurrentHealth(int adj) {
curHealth += adj;
if(curHealth < 0)
curHealth = 0;
if(curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width / 2) * (curHealth / (float)maxHealth);
if(curHealth <= 0){
animation.Play ("death");
yield WaitForSeconds(3);
Application.LoadLevel(2);
}
}
To This:
public IEEnumerator adjustCurrentHealth (int adj)
{
curHealth += adj;
if (curHealth < 0)
curHealth = 0;
if (curHealth > maxHealth)
curHealth = maxHealth;
if (maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width * 0.5f) * (curHealth / (float)maxHealth);
if (curHealth <= 0)
{
animation.Play ("death");
yield new WaitForSeconds(3);
Application.LoadLevel(2);
}
}
If Unity complains you do not have enough return path’s, then after the last if statement you may need to add:
yield return null;
Also calling this method will be different now its a co-routine. You call it using StartCoroutine(adjustCurrentHealth());