I have an enemy teleporter script that randomizes its teleport targets, I am unsure on how to have the isTeleporting boolean set to false when the teleport cooldown is happening and once the cooldown is over the boolean sets back to true to teleport to a target again. This is so my attack script can call my teleporter script to check if the enemy is moving or not in order to attack the target it is at.
Here is my EnemyTeleporter script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyTeleporter : MonoBehaviour
{
private List<Transform> windowTargets = new List<Transform>(); // List of teleport targets
[SerializeField]
private float teleportCooldown = 10f; // Cooldown time between teleports
public bool isTeleporting = false; // Flag to prevent multiple teleports during cooldown
private void Start()
{
// Find all objects tagged with "WinTarget" and populate the windowTargets list
GameObject[] targets = GameObject.FindGameObjectsWithTag("WinTarget");
foreach (GameObject target in targets)
{
windowTargets.Add(target.transform);
}
if (windowTargets.Count == 0)
{
Debug.LogError("No objects found with the tag 'WinTarget'!");
}
else
{
StartCoroutine(TeleportRoutine());
}
}
private IEnumerator TeleportRoutine()
{
while (true) // Infinite loop for continuous teleporting
{
if (!isTeleporting)
{
BeginTeleport();
isTeleporting = true;
// Wait for cooldown duration
yield return new WaitForSeconds(teleportCooldown);
isTeleporting = false;
}
yield return null;
}
}
private void BeginTeleport()
{
if (windowTargets == null || windowTargets.Count == 0) return;
// Select a random target from the list
Transform randomTarget = windowTargets[Random.Range(0, windowTargets.Count)];
// Move the enemy to the selected target's position
transform.position = randomTarget.position;
Debug.Log("Teleported to: " + randomTarget.name);
}
}