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.
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.