- Home /
Pause OnTriggerEnter
I dont understand why this doesn't work. All i am trying to do is pause the game for one sec OnTriggerEnter:
using UnityEngine;
using System.Collections;
public class LevelInfo : MonoBehaviour {
public bool pause;
void Update()
{
if (pause){
Time.timeScale = 0;
}
if (!pause){
Time.timeScale = 1;
}
}
void OnTriggerEnter (Collider col){
if (col.gameObject.tag == "Player"){
StartCoroutine(pauseTime());
print ("Pause in action");
}
}
IEnumerator pauseTime(){
pause = true;
yield return new WaitForSeconds(1f);
pause = false;
}
}
Thank you
Answer by KellyThomas · Dec 29, 2013 at 08:25 AM
WaitForSeconds
runs at Time.timeScale
.
As you set timeScale
to 0 it will never stop waiting.
More detail and a couple of solutions can be found here.
Here is an implementation that monitors Time.realtimeSinceStartup
:
using UnityEngine;
using System.Collections;
public class Pause : MonoBehaviour
{
private float pauseUntil;
private bool paused;
void Update() {
if (paused) CheckPause();
}
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "Player") {
PauseForDuration(1.0f);
}
}
void PauseForDuration(float duration) {
paused = true;
pauseUntil = Time.realtimeSinceStartup + duration;
Time.timeScale = 0.0f;
}
void CheckPause() {
if (Time.realtimeSinceStartup >= pauseUntil) {
Time.timeScale = 1.0f;
paused=false;
}
}
}
That works by itself, but once i put it inside the OntriggerEnter it doesn't seem to work.
I think your code currently has the following behaviour:
In pauseTime():
set pause to true
start waiting for 1 sec
Then in the next Update():
set timeScale to 0
As a result one second of game time will never pass.
Two solutions are available at the question I linked to above.
Please try one of those and tell me how it goes.
The TimeScale make sense Thank you $$anonymous$$elly but that doest explain why this does not work:
using UnityEngine;
using System.Collections;
public class LevelInfo : $$anonymous$$onoBehaviour {
void OnTriggerEnter (Collider col)
{
if (col.gameObject.tag == "Player")
{
Time.timeScale = 0.0000001f;
}
}
}
Are you then calling:
yield return new WaitForSeconds(0.0000001f);
In this case all i want to do is Pause on trigger Enter. But that is the part that doesn't work.
So on: OnTriggerEnter = Time.timeScale =0 (Doesn't run the timescale)