- Home /
HOW can i make my time start and pause?
i have a object and i want when my object is active, the time starts and vice versa when my object is not active, the time will stop. pls help me some scripts C# thank you very much!!
Answer by Hellium · Oct 11, 2017 at 01:24 PM
Attach a script on your object and implement the following functions :
void OnEnable()
{
Time.timeScale = 1 ;
}
void OnDisable()
{
Time.timeScale = 0 ;
}
Answer by Yuvii · Oct 11, 2017 at 12:39 PM
Hey,
let me know if this works the way you want :)
public Gameobject yourObject;
public Update()
{
if(yourObject.active && Time.timeScale == 0)
{
Time.timeScale = 1;
}
else if(!yourObject.active && Time.timeScale == 1)
{
Time.timeScale = 0;
}
}
This isn't the most optimized way to do it actually, because it will check the state of your object at every frame. The best way to do it would be to set the Time.timeScale when you SetActive(true/false) your object. That way it won't have to check every frame, and it will increase performances.
For example let's say the 'P' key enable or disable your object :
void Update()
{
if(Input.GetKeyDown(KeyCode.P))
{
if(!yourObject.active)
{
yourObject.SetActive(true);
Time.timeScale = 1;
}
else
{
yourObject.SetActive(false);
Time.timeScale = 0;
}
}
}