0

I am designing my first game and I am trying to create a time variable with a 5 sec step (like 5 times slower than real time).

This is the where I have the GUI (pasting only relevant parts):

using UnityEngine;
using Assets.Code.Interfaces;
using Assets.Code.Scripts;
using Assets.Code.PowerPlants;
namespace Assets.Code.States

Debug.Log (TimeManager.gametime);
public void ShowIt()
    {

GUI.Box (new Rect (Screen.width - 650, 10, 100, 25), TimeManager.gametime.ToString() );  // GAME TIME HOURS
}

This is where my game time is calculated:

using System;
using UnityEngine;
namespace Assets.Code.Scripts
{
    public class TimeManager
    {
        public static int gametime;
        public TimeManager ()
        {
        gametime = (int)Time.timeSinceLevelLoad / 5;
        }
    }
}

I get no errors, but the value of gametime is always 0. This worked before but is not working anymore and I have no idea why. Any hints?

ClaudioA
  • 327
  • 1
  • 5
  • 20

2 Answers2

1

I think, this is because you set gametime only once in the constructor of TimeManager. So, it will never be updated. Put it in Update, then it will work.

Dieter Meemken
  • 1,937
  • 2
  • 17
  • 22
  • TimeManager is no MonoBehaviour so it has no Update. You got it right tho on the fact that it is set once in the ctor and never updated. – Everts Dec 12 '15 at 18:59
  • Ok, then you could give it a updating method and call that from a another method before whenever you need the new value. – Dieter Meemken Dec 12 '15 at 19:01
  • That you can do indeed but look at my answer (I don't say it is the best answer possible). Unity is already taking care of updating timeSinceLevelLoaded, all he needs is the division. If the call was not made each frame, it would be a bit of a waste to run in Update. But again, you got it right, adding an Update and calling it from a MonoBehaviour is a solution. – Everts Dec 12 '15 at 19:05
1
namespace Assets.Code.Scripts
{
    public class TimeManager
    {
        public static int gametime 
        { 
           get { return (int)Time.timeSinceLevelLoad / 5;  }
        }
    }
}

The ctor is not useful in your case, just add a property that returns the value you need.

Everts
  • 10,408
  • 2
  • 34
  • 45