- Home /
im trying to do an immortal state when my player take damage
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);
}
}
}
Answer by Jessespike · Sep 12, 2016 at 07:29 PM
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;
}
}
Answer by Hanoble · Sep 12, 2016 at 07:18 PM
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);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to Position the object perfectly with the Screen Bounds 0 Answers
How can I change jump direction? 1 Answer
Yield return request never returns 0 Answers