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

Time pauses

Discussion in 'Scripting' started by epochplus5, Nov 6, 2020.

  1. epochplus5

    epochplus5

    Joined:
    Apr 19, 2020
    Posts:
    677
    Is the only way to get a time pause by using a coroutine?
    its pretty messy if you want to have a few time constraints like waiting for an enemy attack and slowing down the fire rate of a weapon. Is this the only way of doing it or is there a smarter way?
     
  2. rubcc95

    rubcc95

    Joined:
    Dec 27, 2019
    Posts:
    222
    Time.time its a float with the number of seconds passed since the start. For example this script triggers YourShotMethod when mouse is pressed, but only one time each 0.5 seconds:

    Code (CSharp):
    1. Weapon : MonoBehaviour
    2. {
    3.     float _nextShot = 0;
    4.     float _weaponRatio = 0.5f;
    5.  
    6.     void Update()
    7.     {
    8.         if (Input.GetMouseButtonDown (0) && _nextShot <= Time.time)
    9.         {
    10.             _nextShot = Time.time + _weaponRatio;
    11.             YourShotMethod ();
    12.         }
    13.     }
    14. }
     
  3. VishwasGagrani

    VishwasGagrani

    Joined:
    May 12, 2018
    Posts:
    81
    You can use Invoke. It calls the specified method once after specified time.
    Use InvokeRepeating if you want to call it again and again.

    Code (CSharp):
    1.  
    2.   void Start()
    3.    {
    4.        Invoke("DelayThisMethodCall", 2.0f);
    5.    }
    6.  
    7.     void DelayThisMethodCall()
    8.    {
    9.      Debug.Log ( "This method has been called after 2 seconds");
    10.  
    11.    }
     
  4. epochplus5

    epochplus5

    Joined:
    Apr 19, 2020
    Posts:
    677
    niiiiiiiiiiiice thanks guys