# How do I pause and unpause gameobjects on is own in the scene without pressing keys in unity3d

I can't get my gameobject to pause or unpause in the scene in Unity3d. I need the game to pause for a couple of seconds maybe longer than unpause by itself. Here is my script :

using UnityEngine;
using System.Collections;

public class hu : MonoBehaviour {
GameObject[] pauseObjects;
public bool isPaused;
void Start () {

pauseObjects = GameObject.FindGameObjectsWithTag("Player");

}

// Update is called once per frame
void Pause () {

{
if(Time.timeScale == 1)
{
Time.timeScale = 7f;

} else if (Time.timeScale == 8f){

Time.timeScale = 1;

}
}
}
}

• Time.timeScale affects your whole scene. It's not a per-gameObject value. – Leo Sep 11 '16 at 12:06
• Also, you're checking for timeScale == 8 but set it to 7. Also, none of those values are paused. Also also you renamed your function to Pause bit didn't remove the comment about the function being Update – Draco18s no longer trusts SE Mar 12 '19 at 19:34

In Unity 5.4 you can use the built-in WaitForSecondsRealtime in your coroutine to safely modify timescale and avoid problem with WaitForSeconds when having timeScale == 0 as @DMGregory mentioned

https://docs.unity3d.com/ScriptReference/WaitForSecondsRealtime.html

So it would be something like :

using UnityEngine;
using System.Collections;

public class WaitForSecondsExample : MonoBehaviour
{

public void PauseAndAutoUnpause(float pauseTime)
{
StartCoroutine(PauseAndAutoUnpauseCoroutine(pauseTime));
}

IEnumerator PauseAndAutoUnpauseCoroutine(float pauseTime)
{
Time.timeScale = 0f;  // set timeScale to 0 will make your game paused
yield return new WaitForSecondsRealtime(pauseTime);
Time.timeScale = 1f; // we unpause the game by setting timeScale to its normal value, 1
}

}


You should use Coroutines.

void Pause(){
StartCoroutine(waitToUnpause);
}

IENumerator waitToUnpause(){
//do the thing to pause game
Time.timeScale = 7f;//or some other method
yield return new WaitForSeconds(7);///or any duration you want
Time.timeScale = 1f;//or some other method
}

• Just beware that if you try to pause the game by setting Time.timeScale to zero, then WaitForSeconds() will never resume the coroutine, since it counts seconds in game time, not realtime. Instead you may need to use a while loop with yield return null to wait a frame each iteration, then check Time.realtimeSinceStartup to determine when to break out & resume. – DMGregory Sep 11 '16 at 13:39
• Also, how would that pause the game? Setting the Time.timeScale to 7f will make the game run seven times faster not pause it. – Leo Sep 11 '16 at 14:53
• I don't know. i have never messed with time scale. as i have commented in the code, tthe person should use their own way and i do not recommend messing with timescale myself – Fatemeh Majd Sep 12 '16 at 19:05