I'm receiving an error saying that "Specified cast is not valid (wrapper castclass)".
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<General>().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;
}
}
Your answer
Follow this Question
Related Questions
NullReferenceException: Object reference not set to an instance of an object 1 Answer
I Need help with scripting a first person camera? 1 Answer
C# Enable component on another GameObject using name of component 1 Answer
Particle System trigger script not working,Particle system trigger script not working 0 Answers