How make: Timer with Time.time
I have a builder who summons a building 10 seconds after colliding with a 2DBoxCollider. I've taken examples from multiple cooldown answers on the forums and all use something similar to what I will show you. Leaving the 2dboxcollider will cancel this build time.
The Problem is that the building is summoned instantly whether or not i set the cooldown to 10f or 1000f.
C#
private float summoningStart = 0f;
public float summonCooldown = 10f;
private bool collisionMade = false;
void OnTriggerEnter2D(Collider2D col) {
if (col.gameObject.tag == "Red Warrior Mage") {
collisionMade = true;
}
}
void SpawnGenerator() {
Instantiate(generator, transform.position, Quaternion.identity);
collisionMade = false;
summoningStart = Time.time;
}
void Update() {
if( Time.time >= summoningStart + summonCooldown && collisionMade == true){
SpawnGenerator();
}
}
And to cancel the build time i do this
void OnTriggerLeave2D(Collider2D col) {
if (col.gameObject.tag == "Red Warrior Mage") {
collisionMade = false;
}
}
So again, what's happening is the building is being summoned instantly, instead of being summoned 10 seconds after OnTriggerEnter2D is called.
Extra Credit: Each second passed is recorded and can be displayed in a visual timer with numbers
@Positive7, This hit the nail on the head. Please make this an answer so I can mark this correct :) :D ^_^
Answer by Positive7 · Sep 07, 2015 at 03:54 PM
Sent from mobile so not tested but try this :
private float summoningStart = 0f;
public float summonCooldown = 10f;
private bool collisionMade = false;
void OnTriggerEnter2D(Collider2D col) {
if (col.gameObject.tag == "Red Warrior Mage") {
summoningStart = Time.time + summonCooldown;
collisionMade = true;
}
}
void SpawnGenerator() {
Instantiate(generator, transform.position, Quaternion.identity);
collisionMade = false;
summoningStart = Time.time + summonCooldown;
}
void Update() {
if( summoningStart <= Time.time && collisionMade == true){
SpawnGenerator();
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612012913im_/https://answers.unity.com/themes/thub/images/avi.jpg)