- Home /
Can't make time go down after picking up a coin,
So what i have is a "coin" which is just a game object to act as a trigger with a script attached to it that does 3 things: play a sound, call a function from my timer script, and then destroy the coin. The audio is played, the coin disappears, but my timer just keeps going with the same time. I think its worth noting that I'm almost brand new to Unity and coding in general, so I still don't understand a large chunk of c#.
Here is my timer
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour {
public Text counterText;
public float seconds, minutes;
bool keepTiming;
private float _time = 0.0f;
// Use this for initialization
void Start ()
{
counterText = GetComponent<Text>() as Text;
StartTimer();
}
void StartTimer()
{
keepTiming = true;
}
private void Update()
{
if (keepTiming)
{
UpdateTime();
}
}
// Update is called once per frame
void UpdateTime()
{
_time += Time.deltaTime;
minutes = (int)(Time.time / 60f);
seconds = (int)(Time.time % 60f);
counterText.text = minutes.ToString("00") + ":" + seconds.ToString("00");
}
public void SubtractTime()
{
_time -= 5.0f;
}
public void StopTimer()
{
keepTiming = false;
}
}
And here's the script i placed on my coin
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinCollect : MonoBehaviour {
public Timer script;
public GameObject trigger;
public AudioSource audioClip;
private void OnTriggerEnter(Collider collider)
{
if (collider.tag == "Player")
{
trigger.SetActive(true);
audioClip.Play();
script.SubtractTime();
Destroy(gameObject);
}
}
private void OnTriggerExit(Collider collider)
{
if (collider.tag == "Player")
{
trigger.SetActive(false);
}
}
}
I'm just really lost on how to fix this, so any advice is greatly appreciated.
,
Answer by Eno-Khaon · Nov 30, 2018 at 05:08 AM
Your minutes and seconds variables are using Time.time rather than your custom-defined _Time variable.
Oh, yah that would make sense. I'll try try to fix that whenever I have a chance. Would i just replace time in Time.time with _time to make it work? Thanks again for the help.
Yep.
Fundamentally, your _Time variable should be the same value as Time.time when you add Time.deltaTime every frame, but then any further changes made to it (removing time for grabbing coins) would be specific to your own, so it's what you should be showing the player.
Answer by BGR521 · Nov 30, 2018 at 09:01 PM
Update: I managed to get it to work now. I was getting a NullReference error but i guess i just didn't have the script selected on my coin. Thank you again for the help.
Your answer
![](https://koobas.hobune.stream/wayback/20220612183033im_/https://answers.unity.com/themes/thub/images/avi.jpg)