Is there a way to teleport player after countdown timer hits zero?
Hi I'm very new to scripting and to unity as well, In my scene, I would like the player to teleport to a certain location after the countdown timer hits zero, is there a way to do this? I research online however it could not help me much thus I am asking here.
I did a basic code timer I found online
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public float timeRemaining = 150;
public bool timerIsRunning = false;
public Text timeText;
private void Start()
{
// Starts the timer automatically
timerIsRunning = true;
}
void Update()
{
if (timerIsRunning)
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
DisplayTime(timeRemaining);
}
else
{
Debug.Log("Time has run out!");
timeRemaining = 0;
timerIsRunning = false;
}
}
}
void DisplayTime(float timeToDisplay)
{
timeToDisplay += 1;
float minutes = Mathf.FloorToInt(timeToDisplay / 60);
float seconds = Mathf.FloorToInt(timeToDisplay % 60);
timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
}
Comment
Best Answer
Answer by Hellium · Aug 02, 2020 at 11:59 AM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class Timer : MonoBehaviour
{
public float timeRemaining = 150;
public bool timerIsRunning = false;
public Text timeText;
public UnityEvent onTimerElapsed; // Declare event
private void Start()
{
// Starts the timer automatically
timerIsRunning = true;
}
void Update()
{
if (timerIsRunning)
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
DisplayTime(timeRemaining);
}
else
{
Debug.Log("Time has run out!");
timeRemaining = 0;
timerIsRunning = false;
onTimerElapsed.Invoke(); // Invoke event
}
}
}
void DisplayTime(float timeToDisplay)
{
timeToDisplay += 1;
float minutes = Mathf.FloorToInt(timeToDisplay / 60);
float seconds = Mathf.FloorToInt(timeToDisplay % 60);
timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
}
// Attach this component to a gameObject
// Add a new entry in the onTimerElapsed event of the Timer component
// Drag & drop the gameObject with this script
// Reference the ResetPlayerPosition method
public class GameManager : MonoBehaviour
{
public Transform player;
public Vector3 startPosition;
// Call this method in the `onTimerElapsed` event of the Timer
// Like you can do with UI buttons
public void ResetPlayerPosition()
{
player.position = startPosition;
}
}