Search code examples
unity-game-engineunity3d-2dtools

Having problems with WaitForSeconds


So i'm trying to make a script for a "follower" which will start following the player on colliding with it. The problem is that i want the follower to wait for a given time before moving towards the player after every time the player will stop.

It works when the player collides with it, It moves toward the player after the given time but when the player stops and moves again the follower sticks with the player instead of waiting till the given time is over. Here's the script:

 void Update () {
     //running is a triggered true on colliding with player.
     if(running == true){
         StopCoroutine(Move());
         StartCoroutine(Move());
     }
 }
 IEnumerator Move(){
     yield return new WaitForSeconds (0.5f);
     Vector2 pos = transform.position;
     Vector2 playerpos = player.transform.position;
     playerpos.y = pos.y;
     transform.position = Vector2.MoveTowards(pos, playerpos, 1f * Time.deltaTime);
 }

Is there something that i'm doing wrong?

Also there is another issue, the follower moves faster then the given speed.

Function for player movement.

void Move(float horizontalinput){
    Vector3 pos = transform.position;
    pos.x += horizontalinput * maxSpeed * Time.deltaTime;
    transform.position = pos;
} 

I'll really appreciate some help with it.


Solution

  • You could try:

    Create a variable called _canMove and set it to false. Then your Update would be:

    private void Update()
    {
        if(_canMove)
        {
            Move();
        }
    }
    

    Your Move method would be the same as it currently is, but minus the WaitForSeconds line. Then when the player stops run the following line which will prevent the Update method from calling the Move method:

    _canMove = false
    

    When the player starts to move again run the following:

    StartCoroutine(ResetCanMove);
    

    This will call ResetCanMove which will wait x-seconds before setting _canMove to true and in turn will cause Update to start calling Move again.

    Here is the ResetCanMove method

    private IEnumerator ResetCanMove()
    {
        yield return new WaitForSeconds(0.5f);
        _canMove = true;
    }