I'm not sure as to why this happened however I'm pretty sure it has something to do with the "Respawn" Coroutine as I receive the error whenever this enemy sprite/ gameobject does respawn. Additionally, the "respawned" enemy sprite does not have its components set as active if someone could help with that as well.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
[Header("Health")]
[Header("Movement")]
[Header("Attack")]
[SerializeField] private float attackDamage = 10f;
[SerializeField] private float attackSpeed = 0.5f;
[SerializeField] private float maxHealth;
[SerializeField] private Transform respawnPoint;
public float speed = 3f;
public Transform trans;
private float canAttack;
private Transform target;
private float health;
public GameObject enemyObj;
Vector3 enemyPosition = new Vector3 (7.71339989f, -3.26340008f, 0f);
private void Start()
{
health = maxHealth;
}
public void TakeDamage(float dmg) {
health -= dmg;
Debug.Log("Enemy Health: " + health);
if (health <= 0)
{
speed = speed * 2f;
Destroy(gameObject);
StartCoroutine(Respawn());
}
}
private void Update()
{
if (target != null)
{
float step = speed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, target.position, step);
}
}
private void OnCollisionStay2D(Collision2D other)
{
if (other.gameObject.tag == "Player")
{
if(attackSpeed <= canAttack)
{
other.gameObject.GetComponent().UpdateHealth(-attackDamage);
canAttack = 0f;
}
else
{
canAttack += Time.deltaTime;
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
target = other.transform;
}
}
IEnumerator Respawn()
{
enemyObj = (GameObject)Instantiate (enemyObj, enemyPosition, Quaternion.identity);
yield return null;
}
}
↧