Home > Enterprise >  How do I add a pause?
How do I add a pause?

Time:01-19

So I am currently trying to make a game and I want one of the features to be when you hit a certain block I called it Obstacle you will pause for 1 second. I just don't know how to add that pause in C#. The script:

using UnityEngine;

public class PlayerCollision : MonoBehaviour {
    public Movememt movement;
         
    void OnCollisionEnter (Collision Collisioninfo)
    {           
       if (Collisioninfo.collider.name == "Obstacle")
        {
            movement.enabled = false;
           // i want the pause here
            movement.enabled = true;
            
        }
    }
}

CodePudding user response:

You can do it using coroutines.

You can change the return value from void to IEnumerator which will allow you to "pause" by yeilding a new WaitForSeconds instance. Here is an example:

IEnumerator OnCollisionEnter(Collision collision)
{           
    if (collision.collider.name == "Obstacle")
    {
        movement.enabled = false;
        yield return new WaitForSeconds(seconds);
        movement.enabled = true;
    }
}

CodePudding user response:

You can use WaitForSeconds with coroutines. For details please go through the link.

yield return new WaitForSeconds(1);

Hope it helps.

CodePudding user response:

You can pause or resume the game by setting the timescale to 0 or back to 1.

void PauseGame()
    {
        Time.timeScale = 0;
    }

void ResumeGame()
    {
        Time.timeScale = 1;
    }
  •  Tags:  
  • Related