How do I change the time on my timer from another script?
So what I'm wondering is how do I affect the text element that the TimeManager class is using to add or remove time? I'm not sure how to access the TimeManager's timeLeft script from the script that is detecting when objects are tapped/clicked.
public class TimeManager : MonoBehaviour {
public float timeLeft;
private Text theText;
void Start () {
theText = GetComponent<Text>();
}
void Update () {
timeLeft -= Time.deltaTime;
theText.text = "" + System.Math.Round(timeLeft, 2);
}
}
public class Tapped_Shape : MonoBehaviour {
void OnMouseDown() {
TimeManager tapped_timer = GetComponent<TimeManager>();
gameObject.GetComponent tapped_timer.timeLeft += 20f;
Destroy (gameObject);
}
}
Answer by Fredex8 · Mar 17, 2016 at 03:47 AM
Just a quick example of how to cache references for you:
public class Tapped_Shape : MonoBehaviour {
private GameObject timeManagerObject;
private TimeManager timeManagerScript;
void Start () {
timeManagerObject = GameObject.Find("nameOfYourObjectInScene");
timeManagerScript = timeManagerObject.GetComponent<TimeManager>();
}
void OnMouseDown() {
timeManagerScript.timeLeft += 20f;
Destroy (gameObject);
}
}
What this is doing is storing the GameObject that holds your TimeManager script as timeManagerObject and then storing the script from that object as timeManagerScript.
Doing this once in start is better than doing it every frame. Obviously I'm just using GameObject.Find as an example here and you will be better off assigning that from the inspector or via another method.
Or, to keep it simple:
timeManagerObject.GetComponent<TimeManager>().timeLeft += 20f;
Your answer
Follow this Question
Related Questions
How to remove/freeze timer on Destroy() 2 Answers
Projectile destruction when time reaches zero 0 Answers
Need help with making disappearing platforms. Error CS1525 1 Answer
I make a timing score script in unity 2D, how i make high score of time?? Script is as follow: 1 Answer
HH:MM:SS game clock with modifiable start time error 1 Answer