I have a function that requires a vector as input. This vector has to be created in some kind of repeating function (I’m using the update method, though I could just as easily use a method with invokerepeating). How do I call this function after say, 1 second? Would something like Invoke(“MyFunc(vector3)”, 1f) work? Or do I have to do something else?
Just run a timer in Update() and call the method as normal when required.
Use a manual timer or learn how to use Coroutines. Coroutines can do everything Invoke can do, and can take parameters as well.
A manual timer is pretty trivial to create. Here’s one that I ended up with based off of a thread a few months back meant to have very minimal impact on performance.
Timer
using System;
using UnityEngine;
[Serializable]
public struct Timer
{
public float Duration;
public bool Repeats = false;
private float nextTriggerTime;
/// <summary>
/// Indicates whether the timer has expired and is ready to trigger.
/// </summary>
public bool HasExpired
{
get
{
if (Time.time < nextTriggerTime)
{
return false;
}
else
{
if (Repeats)
Restart();
return true;
}
}
}
/// <summary>
/// Starts or restarts the timer.
/// </summary>
public void Restart()
{
nextTriggerTime = Time.time + Duration;
}
}
Example
using UnityEngine;
public class Example : MonoBehaviour
{
private Timer timer;
void Start()
{
timer.Duration = 1f;
timer.Repeats = true;
}
void Update()
{
if (timer.HasExpired)
{
SomeMethod();
}
}
}
I only learned maybe a year ago that at some point Unity finally came to their sense and exposed the time as a double directly via Time.timeAsDouble. Since then whenever I find a bit of old code that does timing using floats I’ve been converting it to doubles. Normally I’m really picky about using the smallest datatype possible but in this case doubles are absolutely the way to go.
I didn’t even know that was a thing as I normally search for “Time.whatever” when looking up APIs. Apparently it’s available as for a few of the others as well. ![]()