- Home /
how to access a non static timer to store in highscore
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour {
public float timer = 0f;
public string time ;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
timer +=Time.deltaTime;
time = timer.ToString("0.00");
}
}
This is the Timer.cs. Now i want to store the time in GameState.cs
using UnityEngine;
using System.Collections;
public class GameState : MonoBehaviour {
// Use this for initialization
public string highscoretime;
void Start () {
}
// Update is called once per frame
void Update () {
highscoretime = Timer.time;
}
}
But it says an object reference is required to access Timer.time? Timer is attached to a guitext and gamestate is attached to an empty game object. Thanks in advance.
Answer by aldonaletto · Sep 09, 2013 at 11:42 AM
In this case the easiest solution is to have a reference to the script Timer and assign it in the Inspector: just drag the GUIText object from the Hierarchy to the field Timer Script in the Inspector (or select it with the "dot button"). This field corresponds to the public variable timerScript in the modified GameState script below:
using UnityEngine;
using System.Collections;
public class GameState : MonoBehaviour {
public string highscoretime;
public Timer timerScript; // drag the GUIText here from Hierarchy
// Update is called once per frame
void Update () {
highscoretime = timerScript.time;
}
}
This is based on a nice Unity feature: declaring a public variable as type Timer allows it to accept dragging any object that has the script Timer attached - the variable actually stores the reference to the script Timer added to that object, not to the object itself.
Thank you very much it worked!! .Just dragged timer to game object--->game state script.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Fade in AudioLister over time #c 1 Answer
Spawning game Object after a period of time 2 Answers
Getting a Code to Run at a Specific Time of Day Even if App is Off. 1 Answer