Home > Software engineering >  Make the game wait for seconds
Make the game wait for seconds

Time:06-27

i'm creating a sort of Five Nights at Freddy's game in Unity, using c# code. My idea was to make the animatronic jumpscare the player, and then wait for like 3 seconds and at the end make the player go back to the main menu. How can i make the game (or the code) wait for that 3 seconds before going to the menu? Thank you

CodePudding user response:

have a look at this example from the official documentation

https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    // Launches a projectile in 2 seconds

    Rigidbody projectile;

    void Start()
    {
        Invoke("LaunchProjectile", 2.0f);
    }

    void LaunchProjectile()
    {
        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5.0f;
    }
}

So you can add a Restart method to your class and invoke it with 3 seconds of delay in your jumpscare function

void JumpScare()
{
    Invoke("Restart", 3.0f);
}
void Restart()
{
 // don't forget  using UnityEngine.SceneManagement; at top of your file
 SceneManager.LoadScene(0); // index of your scene in builds settings
}

CodePudding user response:

You can use async await on the function you use to take the player to the main menu. You need to add the namespace "using System.Threading.Tasks". Here is an example code

using UnityEngine;
using System.Threading.Tasks;

public class Play_audio : MonoBehaviour
{

    async void Start()
        {
  
         await Task.Delay(1000)
         Your_fncton();   
            
        }
}

Source: https://vionixstudio.com/2021/11/01/unity-async-await/

  • Related