so I am trying to make a land mine for my 2D game and everything works except for the delay. I have no idea why its not working but I have used Coroutines before but this time wait for seconds doesn’t work.
using System.Threading.Tasks;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LandmineMushroom : MonoBehaviour
{
public int PlayerDamage = 10;
public float TimeTillBoom = 0.5f;
private PlayerHeath johnHealth;
private PlayerHeath jamesHealth;
private AudioSource audio;
private GameObject Mush;
private ParticleSystem par;
private GameObject Debris;
public Animator anim;
private GameObject John;
private GameObject James;
private bool CountDownStarted = false;
void Awake()
{
Mush = GameObject.Find("MushroomLandMine");
audio = Mush.GetComponent<AudioSource>();
Debris = GameObject.Find("MushroomDebris");
par = Debris.GetComponent<ParticleSystem>();
John = GameObject.Find("JohnWeapon/Heath");
johnHealth = John.GetComponent<PlayerHeath>();
James = GameObject.Find("James");
jamesHealth = James.GetComponent<PlayerHeath>();
}
private HashSet<Collider2D> processedColliders = new HashSet<Collider2D>();
void OnTriggerEnter2D(Collider2D other){
if (other.CompareTag("John"))
{
StartCoroutine(JohnEnter());
}
if (other.CompareTag("James"))
{
StartCoroutine(JamesEnter());
}
}
private IEnumerator JohnEnter()
{
anim.SetTrigger("GoUp");
if (CountDownStarted == true)
{
//if 2 people walk over it then it will go BOOM
Boom();
}else
{
CountDownStarted = true;
}
anim.SetTrigger("ExplosionStarted");
//if only one person walks on it then it counts down then BOOM
yield return new WaitForSeconds(TimeTillBoom);
Boom();
}
private IEnumerator JamesEnter()
{
anim.SetTrigger("GoUp");
if (CountDownStarted == true)
{
//if 2 people walk over it then it will go BOOM
Boom();
}else
{
CountDownStarted = true;
}
//if only one person walks on it then it counts down then BOOM
anim.SetTrigger("ExplosionStarted");
yield return new WaitForSeconds(TimeTillBoom);
Boom();
}
void Boom()
{
audio.Play();
par.Play();
// Check if John is active in the scene
if (John.activeInHierarchy)
{
float distanceToJohn = Vector2.Distance(this.transform.position, John.transform.position);
UnityEngine.Debug.Log("Distance to John: " + distanceToJohn);
// Apply damage to John if he is within the explosion radius
if (distanceToJohn < 5)
{
johnHealth.WayOfDeath = "Sat On Landmine";
johnHealth.UpdateHeath(100);
}
}
// Check if James is active in the scene
if (James.activeInHierarchy)
{
float distanceToJames = Vector2.Distance(this.transform.position, James.transform.position);
// Apply damage to James if he is within the explosion radius
if (distanceToJames < 0.5f)
{
jamesHealth.UpdateHeath(PlayerDamage);
}
}
// Destroy or disable the landmine after exploding
Destroy(gameObject);
}
}