- Home /
Adding time to timer with pickup
Hello, I'm trying to used the script attach to my player to +10 to my timeLeft on the other script attach to the GUI. The problem is it compile ok but the timer does not increase after the pickup. Any guidance will be greatly appreciate. Thank you
Player
using UnityEngine; using System.Collections;
public class Player : MonoBehaviour
{
CountdownTimer_test countdownTimer_test;
void Update ()
{
// call countdownTimer_test
countdownTimer_test = GetComponent<CountdownTimer_test>();
}
//pick up
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "PickUp")
{
//add time
Destroy(other.gameObject);
//
countdownTimer_test.timeLeft += 10;
}
}
}
CountdownTimer_test(GUI)
using UnityEngine;
using System.Collections;
public class CountdownTimer_test : MonoBehaviour
{
public float timeLeft = 50.0f;
public void Update()
{
timeLeft -= Time.deltaTime;
if (timeLeft <= 0.0f)
{
// End the level here.
//guiText.text = "You ran out of time";
Application.LoadLevel("learningunity_02");
}
else
{
guiText.text = "Time left = " + (int)timeLeft + " seconds";
}
}
}
Never use yield or coroutines. They are only for specific advanced use.
You use
Invoke()
.
For timers in Unity. It's incredibly simple. Search on this site for 10000s of examples.
http://answers.unity3d.com/questions/543410/need-delay-for-powerup.html
Answer by TrickyHandz · Oct 01, 2013 at 04:24 AM
The reference to "CountdownTimer_Test" is not going to have a reference on the player object when you are trying to assign it because GetComponent() is only looking for components on the object that has the "Player" script attached to it. You can solve this by making a public variable to hold a reference that you can assign in the inspector like this:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public CountdownTimer_test countdownTimer_test;
void Update ()
{
// You won't need the assignment in
// Update() anymore since it can be
// assigned in the Inspector window
}
//pick up
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "PickUp")
{
//add time
Destroy(other.gameObject);
countdownTimer_test.timeLeft += 10;
}
}
By adding the variable above, you can simply drag the object that has the "CountdownTimer_Test" component on it into the variable slot in the inspector and Unity will find the reference to the script.
Hello, TrickyHandz
Thank you very much for the help and explanation I am very new at this. Your instruction is very easy to follow,it work now.
Thank again,have a good day!