- Home /
Can anyone tell how can i add 2 seconds to my TIMER from another script ?
SO i have a script for maintaining timer , but i want to access it from another script and add 2 seconds whenever "if"( condition is true) is used
THIS IS TIMER SCRIPT
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Timer : MonoBehaviour {
public float myTime = 30f;
// Update is called once per frame
void Update () {
GetComponent<Text>().text = (myTime -= Time.deltaTime).ToString("f0");
if(myTime<=0) {
Debug.Log("GAME OVER");
}
}
}
Now i have tried accessing it from this script , but it seems to restart my timer rather than adding 2 seconds
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class onClick1 : MonoBehaviour {
public Text ScoreText;
private int Count = 10;
private int wrongAnswer = -5;
public bool hello;
**private float RightAnswer = 2.0f;**
public void SayHello( bool hello = false ) {
if (GetComponent<Image> ().color == GameObject.FindGameObjectWithTag ("DisplayButton").GetComponent<Image> ().color) {
GameObject thePlayer = GameObject.FindGameObjectWithTag("GameController");
DisplayColor displayColor = thePlayer.GetComponentInChildren <DisplayColor>();
ChangeColor[] changeColors = thePlayer.GetComponentsInChildren <ChangeColor>();
foreach(ChangeColor changeColor in changeColors ) {
Debug.Log(changeColor .gameObject.name);
changeColor.ColorME();
}
**Timer timer = thePlayer.GetComponentInChildren<Timer>();**
hello = true;
displayColor.changeColor();
**timer.myTime =+ RightAnswer;**
ScoreText.text = "SCORE: " + Count;
} else if (GetComponent<Image> ().color != GameObject.FindGameObjectWithTag ("DisplayButton").GetComponent<Image> ().color) {
hello = false;
ScoreText.text = "SCORE: " + wrongAnswer;
}
}
}
Answer by Nerevar · Jun 17, 2015 at 07:23 AM
**timer.myTime =+ RightAnswer;**
It should be "+=" and not "=+", "=+" is equivalent to "=".
Answer by HammerCar · Jun 17, 2015 at 10:04 AM
On line 35 there is
**timer.myTime =+ RightAnswer;**
It should be "+=" not "=+".
Thank you guys for helping me , but now my timer seems to go negative , so if you can help me with that.
It might be because in your timer script there is this.
GetComponent<Text>().text = (myTime -= Time.deltaTime).ToString("f0");
Here you are setting the myTime value so try to use only "-" insted of "-=".
You are actually doing a countdown? that is increased everytime there is a right answer? the game should end when your countdown reaches 0 is that it?
Yes Nerevar i want my game to end and timer to stop after it reaches 0, but right now it seems to go negative
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Timer : $$anonymous$$onoBehaviour {
public float myTime = 20f;
// Update is called once per frame
void Update () {
GetComponent<Text>().text = (myTime - Time.deltaTime).ToString("f0");
if(myTime<=0) {
Debug.Log("GA$$anonymous$$E OVER");
}
}
}