Why is my script causing Unity to crash?
I have created a script that makes an enemy deal damage over time to a player from a raycast but it is making Unity crash once I'm in the required range for the enemy to move and deal damage. Anyone know why?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMove : MonoBehaviour
{
public Transform target;
public Transform player;
public float enemySpeed;
public int moveTrigger = 1;
public bool isAttacking;
public int AttackTirgger;
public float distanceFromPlayer;
void Update()
{
distanceFromPlayer = Vector3.Distance(target.transform.position, player.transform.position);
if (distanceFromPlayer <= 10 && moveTrigger == 1)
{
transform.LookAt(target);
if (!isAttacking)
StartCoroutine(EnemyDamage());
}
if (distanceFromPlayer < 10 && moveTrigger == 1 && distanceFromPlayer > 3)
{
transform.Translate(Vector3.forward * enemySpeed * Time.deltaTime);
}
}
IEnumerator EnemyDamage()
{
isAttacking = true;
while (distanceFromPlayer <= 10)
{ // in range
RaycastHit PlayerHit;
if (Physics.Raycast(target.transform.position, target.transform.forward, out PlayerHit))
{
Target target = PlayerHit.transform.GetComponent<Target>();
if (target != null)
{
GlobalHealth.playerHealth -= 1;
yield return new WaitForSeconds(2);
}
}
}
isAttacking = false; // out of range
yield return null;
}
}
Answer by yummy81 · May 03, 2020 at 07:16 AM
The problem lies in the while loop. There is the condition that the coroutine yields new WaitForSeconds(2) if and only if ray cast from the target hits the object which has Target component attached to. But there is no condition what it should yield if the Target component is not found. In that case Unity freezes. At first move "yield return null" inside while loop, not outside. Next, if you are calculating distance between the target and the player, you should look for the component on the player object, not on the target, or you did not attach Target component to the player object.