Hi, I’m sorry if this question has been asked already but I cant find any answers that apply to my specific scenario. I want to create a coroutine before I respawn the player in my game and also when the player gets hit (to not allow the player to move for a certain time) but for some reason my game completely ignores the coroutine and runs as if it wasn’t there. Note that I am running the coroutine in a singleton class. Also daze time is set to 0.3 in the referenced script. I am sort of new to coroutines… please help me if I am doing it wrong. Also, I don’t think respawn method is the problem but I posted it anyway, in case I am wrong.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour {
public static PlayerManager Instance {get; private set;}
public CharacterController2D character;
public int lives = 2;
[HideInInspector]
public bool isDead;
[HideInInspector]
public bool HandleInput = true;
[SerializeField]
private float _health = 100f;
public float health
{
get
{
return _health;
}
set
{
if (value <= 0f) {
_health = 0f;
} else if (value >= 100f) {
_health = 100f;
} else {
_health = value;
}
}
}
public int attack;
public float defense;
public float speed;
public float jumpFactor;
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad (gameObject);
}
else
{
Destroy (gameObject);
}
}
void Update()
{
if (health == 0 || Input.GetKeyDown(KeyCode.O))
{
Kill ();
}
}
public void Kill()
{
HandleInput = false;
character.animator.SetTrigger("die");
StartCoroutine (KillCo());
Respwan (LevelManager.Instance.checkpoints);
}
private IEnumerator KillCo()
{
yield return new WaitForSeconds (character.animator.GetCurrentAnimatorClipInfo(0).Length);
yield return new WaitForSeconds(3f);
}
public void Damage (float damage)
{
character.timer = 0;
health -= damage * (1 / defense);
character.animator.SetTrigger ("isHit");
character.GetComponent<SpriteRenderer> ().color = new Color32 (249, 86, 86, 255);
HandleInput = false;
StartCoroutine (DamageCo());
HandleInput = true;
character.GetComponent<SpriteRenderer> ().color = new Color32 (255, 255, 255, 255);
}
private IEnumerator DamageCo()
{
yield return new WaitForSeconds (character.dazeTime);
}
public void Respwan (Transform[] checkpoint)
{
lives--;
if (lives == 0)
{
character.transform.position = checkpoint [0].position;
lives = 2;
HandleInput = true;
health = 100f;
} else {
for (int i = 0; i < checkpoint.Length; i++)
{
if (i == checkpoint.Length-1)
{
character.transform.position = checkpoint [i].position;
HandleInput = true;
health = 100f;
return;
}
var distance = character.transform.position.x - checkpoint [i].transform.position.x;
var toNextCheckpoint = character.transform.position.x - checkpoint [i+1].transform.position.x;
if (distance >= 0 && toNextCheckpoint < 0) {
character.transform.position = checkpoint [i].position;
HandleInput = true;
health = 100f;
return;
}
}
}
}
}