Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to stop game for a few seconds?

Discussion in 'Scripting' started by wampirelol, Nov 9, 2022.

  1. wampirelol

    wampirelol

    Joined:
    May 29, 2019
    Posts:
    1
    Hey, I don't know anything about game development and I started to watch 'How to do snake game in Unity' video on youtube and I want to do some modifications to my project to learn development.

    In this tutorial, if snake will get trigger with obstacles, game will reset and snake is restarting at the initial position immediately. I want to add some audio when the snake is dying, so I want to add a few seconds long cooldown to recreate the snake at the initial position after dying.

    Here is the code :

    private void ResetState()
    {
    for (int i = 1; i < _segments.Count; i++)
    {
    Destroy(_segments.gameObject);
    }
    _segments.Clear();
    _segments.Add(this.transform); //I want this code wait for a few seconds//
    this.transform.position = Vector3.zero;
    }

    Thanks already for your help, if you explain "Why did you write that code?", "What would this code do?" it will help me more.

    Sorry for bad grammar. :(
     
  2. LilFire

    LilFire

    Joined:
    Jul 11, 2017
    Posts:
    74
    Best way to do this is to use Coroutines https://docs.unity3d.com/Manual/Coroutines.html.
    Your reset fonction should be like this.

    Code (CSharp):
    1. private IEnumerator ResetState()
    And you call it like that.

    Code (CSharp):
    1. StartCoroutine(ResetState());
    This way you can wait inside your coroutine by using

    Code (CSharp):
    1. yield return new WaitForSeconds(1f);
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
  4. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Nice!
     
    Kurt-Dekker likes this.