Question by
rodpadev · Oct 15, 2020 at 07:19 PM ·
timerdestroy object
My Timer instance is not destroying itself and isn't even counting properly.
I'm making a timer for my spawner because I don't want to use coroutines and I thought I had it all figured out but it isn't really working, the timer and I think it isn't destroying itself either. I'm either very close or so far away from achieving this.
Here is my MonoTimer.cs,
basically using Time.deltaTimer to count
namespace TimerLib
{
public class MonoTimer : MonoBehaviour
{
Action action = null;
float duration = 1f;
public void _InvokeActionRepeating(float duration, Action action) {
this.duration = duration;
this.action = action;
}
void Update() {
if (action != null) {
duration -= Time.deltaTime;
if (duration <= 0f) {
action();
Destroy(gameObject);
}
}
}
}
}
Here is my Timer class, that instantiates the MonoTimer and starts the whole process
using System;
using UnityEngine;
namespace TimerLib
{
public class Timer
{
public static void CreateWithAction(float duration, Action action) {
GameObject gameObjectInstance = new GameObject("Timer", typeof(MonoTimer));
MonoTimer monoTimerInstance = gameObjectInstance.GetComponent<MonoTimer>();
monoTimerInstance._InvokeActionRepeating(duration, action);
}
}
}
And here's me calling creating a new instance of CreateTimer and starting the whole thing;
private void Update() {
TimerLib.Timer.CreateWithAction(1f, InstantiatePrefab);
}
Comment
Your answer
Follow this Question
Related Questions
Add time when collecting objects js 2 Answers
How to destroy the most ancient clone? 0 Answers
timer stopwatch 2 Answers