How do I add a teleport cooldown?

Hi, I’m sorry for any messy code, I’m relatively new to this. I made a working teleport in Unity but whenever I teleport from one of the teleports to the other, I wanna make it so there’s a 5 second cooldown before you can use the teleporter again. So I used IEnumerator, added 5 seconds before “justTeleported” became false again, but when I teleported, I instantly got teleported back, and had to wait 5 seconds before I could try again. So my though was maybe I’m touching the trigger too quickly, before it can become false, that’s why I added the two seconds. But now, whenever I get on the teleporter, it goes from true to false to true a couple times, and then I eventually get teleported back to where I came from. If anyone could help, I would be very thankful. Thank you.

{
public Transform Destination;
bool justTeleported;
public GameObject Player = GameObject.FindGameObjectWithTag(“Player”);

// Start is called before the first frame update
void Start()
{
    justTeleported = false;
}

private void Update()
{
    print(justTeleported)
}

private void OnTriggerEnter2D(Collider2D coll)
{
    if (coll.gameObject.tag == "Player" && justTeleported == false)
    {
        StartCoroutine("Cooldown");
    }
}

IEnumerator Cooldown()
{
    justTeleported = true;
    yield return new WaitForSeconds(2f);
    Player.transform.position = Destination.transform.position;
    yield return new WaitForSecondsRealtime(5f);
    justTeleported = false;
}

The issue is that you have this script on both Teleports. You are setting true on the teleport you have left but are arriving at a different Teleport where the value is false so you get shot back immediately.

The solution is to put this script on the player instead. It’s the player who is moving and who needs the true/false. You’ll need a slight modification (don’t need to test for tag of Player, for example) but it should work without problem.

Since I guess your teleport teleports the player to another teleport, what you could do is have a reference on your teleport script to the teleport it is connected to. Then, when the teleport has to teleport the player, use the variable referencing the other teleport and run your cooldown coroutine on that referenced teleport.

However, coroutines can only be started from their own monobehaviour. So don’t do this:

StartCoroutine(teleportDestination.Cooldown);

Instead, do this:

teleportDestination.StartCoroutine("Cooldown");

This way you call the coroutine from the right script, and yield operations are called properly.