- Home /
start/stop timer when a player enters/exits a room,start/stop timer when player enters/exits a room?
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 in a txt, xml etc file. Any idea on how to approach that?
Answer by SkaredCreations · Mar 08, 2018 at 07:44 PM
Create an object with a Collider component (Box/Sphere/Capsule) as large as your room with its property Is Trigger set to true (checked in the inspector) and attach the following script to it (change the tag name in the code with what you've set in your player object):
using UnityEngine;
public class RoomTimer : MonoBehaviour
{
public float maxTimer = 10f;
bool advance;
float timer;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
timer = maxTimer;
advance = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
advance = false;
}
}
void Update()
{
if (advance && timer > 0f)
{
timer = Mathf.Max(0f, timer - Time.deltaTime);
Debug.Log("Time remaining: " + timer);
}
}
}
The above script has the max timer as property so you can set it from inspector, but you can also have it stored in a txt/xml etc placed in your Resources directory and load the value in Start by using for example (sample code to load Resources/file.txt):
void Start()
{
TextAsset txtFile = Resources.Load<TextAsset>("file");
maxTimer = float.Parse(txtFile.text);
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# and XML Question 1 Answer
Save and Load data from Local XML file won't work 1 Answer
How to save player datas (username, password, etc.) in xml file [only c#] 2 Answers