im trying to do an immortal state that when my player takes damage but my TakeDamage method not working
[SerializeField]
private float immortalTime;
private bool immortal = false;
public IEnumerator TakeDamage(int dmg)
{
if (!immortal)
{
currentPlayerHealth -= dmg;
graphics.GetComponent<Animator>().SetTrigger("damage");
immortal = true;
StartCoroutine (IndicateImmortal());
yield return new WaitForSeconds (immortalTime);
immortal = false;
}
}
private IEnumerator IndicateImmortal()
{
while (immortal)
{
spriteRenderer.enabled = false;
yield return new WaitForSeconds (.1f);
spriteRenderer.enabled = true;
yield return new WaitForSeconds (.1f);
}
}
then here is my Damage source script
using UnityEngine;
using System.Collections;
public class Spike : MonoBehaviour {
//[SerializeField]
public int damage;
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
other.GetComponent<Player> ().TakeDamage (damage);
}
}
}
Coroutines needs to be started with StartCoroutine. You’re calling TakeDamage as if it was a normal function. Try this:
public void TakeDamage(int dmg)
{
StartCoroutine(TakeDamage_Coroutine(dmg));
}
IEnumerator TakeDamage_Coroutine(int dmg)
{
if (!immortal)
{
currentPlayerHealth -= dmg;
graphics.GetComponent<Animator>().SetTrigger("damage");
immortal = true;
StartCoroutine (IndicateImmortal());
yield return new WaitForSeconds (immortalTime);
immortal = false;
}
}
Hanoble
September 12, 2016, 7:18pm
3
TakeDamage is a coroutine, which means you cannot start it like you attempted here in your code:
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
other.GetComponent<Player> ().TakeDamage (damage);
}
}
Instead you need to use the StartCoroutine like you did when TakeDamage() starts the IndicateImmortal() coroutine. You could also turn TakeDamage into a regular method, and have it start the coroutine. This is typically better, as the object that starts the coroutine also manages it. An example of that would be this:
public void TakeDamage(float damage)
{
StartCoroutine(TakeDamageCoroutine());
}
private IEnumerator TakeDamageCoroutine()
{
if (!immortal)
{
currentPlayerHealth -= dmg;
graphics.GetComponent<Animator>().SetTrigger("damage");
immortal = true;
StartCoroutine (IndicateImmortal());
yield return new WaitForSeconds (immortalTime);
immortal = false;
}
}
Then in the other script you call:
public int damage;
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
other.GetComponent<Player> ().TakeDamage (damage);
}
}