Search Unity

Function called too quickly

Discussion in 'Scripting' started by HarryWhitelegg02, Mar 29, 2020.

  1. HarryWhitelegg02

    HarryWhitelegg02

    Joined:
    Mar 11, 2020
    Posts:
    39
    I want a function in my script to be called after waiting for a second, dk if this is even possible. Someone pls help.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GameMaster : MonoBehaviour
    6. {
    7.     public static GameMaster gm;
    8.     public Transform playerPrefab;
    9.     public Transform spawnPoint;
    10.     public bool playerIsRespawned;
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.         if (gm == null)
    16.         {
    17.             gm = GameObject.FindGameObjectWithTag("GM").GetComponent<GameMaster>();
    18.         }
    19.  
    20.     }
    21.  
    22.     public void RespawnPlayer()
    23.     {
    24.         playerPrefab.transform.position = spawnPoint.transform.position;
    25.         // I want the PlayerIsNotDead() function to call after one second that the RespawnPlayer() function is called
    26.         PlayerIsNotDead();
    27.     }
    28.     void PlayerIsNotDead()
    29.     {
    30.         playerPrefab.GetComponent<PlayerMovement>().IsPlayerDead = false;
    31.     }
    32. }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Off the top of my head, here are a few ways to add a delay.
    First is using Invoke. It works, but I don't like the fact it is string based, so no compiler time checking for errors.
    Second is a coroutine. Essentially a method that also allows you to add yields in it for time delays.
    Third is your own timer that you start and it updates in an Update method. Once the timer passes a set amount, you can call your PlayerIsNotDead method.

    In this case, I would probably pick the second or third option.
     
  3. Dextozz

    Dextozz

    Joined:
    Apr 8, 2018
    Posts:
    493