I want to put a delay on the characters movement every time an arrow button is pressed so the player can't just spam move, but for some reason my IEnumerator function doesn't work and it doesn't wait. I'm not sure if I'm using it wrong since I'm getting back into unity. I'm using version 2019.3.14f1 if that helps.
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;
public class Movement : MonoBehaviour
{
void Start()
{
transform.position = new Vector3(0, 0, 0);
}
void Update()
{
CalculateMovement();
}
private IEnumerator delay()
{
yield return new WaitForSeconds(1);
}
void CalculateMovement()
{
if (Input.GetKey(KeyCode.UpArrow))
{
if (transform.position.y != 4)
{
StartCoroutine(delay());
transform.position += new Vector3(0, 1, 0);
}
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
if (transform.position.y != -4)
{
StartCoroutine(delay());
transform.position += new Vector3(0, -1, 0);
}
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
if (transform.position.x != 4)
{
StartCoroutine(delay());
transform.position += new Vector3(1, 0, 0);
}
}
else if (Input.GetKeyDown(KeyCode.LeftArrow))
{
if (transform.position.x != -4)
{
StartCoroutine(delay());
transform.position += new Vector3(-1, 0, 0);
}
}
}
}