Making an enemy go back to its spawn after losing target
Hey everyone, this is my enemy script - it has everything (the enemy runs after the player when he is inside a circle collider attached to him). But this is not the problem - I'm trying to make it so when the enemy loses sight of the player the enemy has to return to its spawnpoint 10 seconds after waiting.
This is the code for my enemy (at the bottom in IENumerator(ReturnToSpawn()) is what I've already tried with no success):
public class EnemyMovement : MonoBehaviour
{
public float moveSpeed;
public int maxHealth = 20;
public int currentHealth;
public HealthBar healthBar;
public GameObject EnemyHealthBar;
private Transform target;
public Animator animator;
private bool isWalking;
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
private void Update()
{
if(target != null)
{
float step = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, target.position, step);
EnemyHealthBar.active = true;
isWalking = true;
animator.SetBool("isWalking", isWalking);
}
else
{
EnemyHealthBar.active = false;
isWalking = false;
animator.SetBool("isWalking", isWalking);
//StartCoroutine(ReturnToSpawn());
}
animator.SetFloat("Horizontal", target.position.x - transform.position.x);
animator.SetFloat("Vertical", target.position.y - transform.position.y);
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Player")
{
target = other.transform;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if(other.gameObject.tag == "Player")
{
target = null;
}
}
/*IEnumerator ReturnToSpawn()
{
yield return new WaitForSeconds(10f);
target = spawn;
float step = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, target.position, step);
if(transform.position == target.position)
{
isWalking = false;
}
}*/
/*void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}*/
}
And this is the enemy script attached to my enemy in the inspector in case you need it:
Also, I tried adding a parent to the enemy with the parent's position being now set with the enemy's position on the map, and the enemy child's position being set as 0, 0. I made it so when the enemy stops chasing you it sets the target to the enemy parent but I still didn't find success with it. Every bit of help would be much appreciated.