- Home /
Start/Stop Timer when player enters/exits a specific space?
Hi, guys. I think it might be pretty easy but I am a bit stuck. I wan to set a timer to run when the player enters a room and stop when the player goes out of the room. I want to store this duration somewhere. Any idea on how to approach that?
Comment
Best Answer
Answer by $$anonymous$$ · Aug 10, 2017 at 04:32 PM
C#:
using UnityEngine;
public class YourScriptName : MonoBehaviour
{
public enum ByType {ByName,ByTag}
public ByType byType = ByType.ByTag;
public string typeName = "Player";
public float timer = 0;
public void OnTriggerStay (Collider other)
{
if(byType == ByType.ByName && other.name == typeName)timer += Time.deltaTime;
if(byType == ByType.ByTag && other.tag == typeName)timer += Time.deltaTime;
}
}
-JavaScript:
public enum ByType {ByName,ByTag}
public var byType : ByType = ByType.ByTag;
public var typeName : String = "Player";
public var timer : float = 0;
public function OnTriggerStay (other : Collider)
{
if(byType == ByType.ByName && other.name == typeName)timer += Time.deltaTime;
if(byType == ByType.ByTag && other.tag == typeName)timer += Time.deltaTime;
}
Put This Script On A GameObject With Box Collider, And Enable (Is Trigger) On The Box Collider And Set The Size And Position In The Room, And Done.
Hope It Helps.
Yeah,man it was really helpful. But do you know how can I store these numbers after? Because now I can check the timer during runtime but after pausing the game it disappears.
Your answer
![](https://koobas.hobune.stream/wayback/20220612132421im_/https://answers.unity.com/themes/thub/images/avi.jpg)