- Home /
Timer Countdown not subtracting value.
I'm trying to subtract 20 seconds from a timer variable on another script once the player enters a trigger. The only problem is that the value is not changing once triggered.
Any ideas?
The Player 1 script:
var p2 : GameObject;
var p2Timer : float;
function Update (){
p2Timer = p2.GetComponent.<Player2Controller>().p2timerCountdown;
}
function OnTriggerEnter(other : Collider){
if (other.tag == "P2Goal"){
p2Timer -= 20;
print("20 seconds subtracted from player 2");
}
}
Player2Controller:
var timerActive : boolean = false;
var p2timerCountdown : float = 120;
function Update (){
//Activate timer here:
timerActive = true;
if (timerActive == true){
p2timerCountdown -= Time.deltaTime;
}
if (p2timerCountdown <= 0){
p2timerCountdown = 0;
print("Player 2 elimated");
}
}
Answer by Tobychappell · May 28, 2018 at 07:59 AM
A float is a value type. You want a reference to the player timer via the player object, then on OnTriggerEnter you'd reduce the players timer via the reference.
I'd suggest you do the following in the Player1 script:
Create a Player2Controller variable called player2 and use unity to assign it like you are doing for the p2 GameObject.
public Player2Controller player2;
Remove the whole update method.
Remove the variable p2 and p2timer and all lines of code using it.
In your OnTriggerEnter method, instead of reducing the p2timer, do:
player2.p2timercountdown -= 20;
Consider reading this for a better understanding of structs and classes.
Your answer
Follow this Question
Related Questions
timer not ticking down 2 Answers
How do I make the timeScale not affect the timer? 1 Answer
GetComponent ? help! 1 Answer
get component javascript from a c# script 3 Answers
Setting Scroll View Width GUILayout 1 Answer