I’m new to unity and I am trying to create a Flappy Bird game for a school project. Everything is working fine except I can’t find a way to reload my timer when the game is over. I’m using the following lines:
void OnGUI()
{
double myTimer;
myTimer = Math.Round(Time.fixedTime, 1);
GUI.Box(new Rect(500, 550, 100, 20), myTimer.ToString());
}
// Update is called once per frame
void Update () {
if (gameOver == true && Input.GetKeyDown(KeyCode.Space))
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); //startar om spelet
}
}
When I have hit something and hit space the scene reloads, however the timer doesn’t. So for example if I hit something after playing for 15 seconds and hit space the game will restart but the timer will start counting in the next scene at 15 seconds. Is there an easy way to fix this in C#?
Have you tried this? Also, declare mytimer outside the OnGUI() method, so that all your methods can access it.
double mytimer;
void Start()
{
mytimer = 0;
}
void Update()
{
if (gameOver == true))
{
mytimer = 0;
}
}
@EdwinChua
I copied your code but it didn’t change anything, when I hit an object and restart the timer doesn’t reset. Declaring the value 0 to myTimer doesn’t seem to work when using it as OnGUI (). Here is my entire script as of now:
public class GameControl : MonoBehaviour {
public static GameControl instance; //gör det möjligt att anropa denna kod från andra koder genom att anropa instance.
public GameObject gameOverText;
public bool gameOver = false;
public float speed = -1.5f;
double myTimer;
// Use this for initialization
void Awake ()
{
if(instance==null)
{
instance = this;
}
}
void Start()
{
myTimer = 0;
}
void OnGUI()
{
myTimer = Math.Round(Time.fixedTime, 1);
GUI.Box(new Rect(500, 550, 100, 20), myTimer.ToString());
}
// Update is called once per frame
void Update () {
if(gameOver==true)
{
myTimer = 0;
}
if (gameOver == true && Input.GetKeyDown(KeyCode.Space))
{ SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); //startar om spelet
}
}
public void BirdDead()
{
gameOverText.SetActive(true); //aktiverar game over texten i spelet
gameOver = true;
}
}
Pardon my indenting…