My unity project is freezing and there are no errors before clicking play button after that it freezes the code:
In this code I am trying to detect if the player is triggering enemy collider with OnTriggerStay2D
so if it does I want the code to add score every second with IEnumerator
function. But if the player is not colliding with the enemy for more than 2 seconds it gets destroyed.
The code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trigger : MonoBehaviour
{
public GameObject other;
bool touching = false;
int score = 0;
public void Update()
{
AddScore();
}
private void OnTriggerStay2D(Collider2D other)
{
Debug.Log("Touching");
touching = true;
}
public void AddScore()
{
if(touching == true)
{
while (touching == true)
{
score ;
StartCoroutine(wait());
}
Debug.Log(score);
}
else
{
Debug.Log("Not Touching");
StartCoroutine(waiter());
}
}
IEnumerator waiter()
{
yield return new WaitForSecondsRealtime(2);
Destroy(other);
}
IEnumerator wait()
{
yield return new WaitForSecondsRealtime(1);
}
}
CodePudding user response:
Just delete while (touching == true)
, that is breaking your game.
The if condition should be enough for the logic.