- Home /
Periodically updating frame conditionally - Time.deltaTime
I'm trying to move an object based on an array of positions values.. i.e. at a fixed interval of time (say 10ms), I want to index into the next element of the array and update the position
I understand Time.deltaTime can be used like this to update the frame periodically:
void Update ()
{
transform.Rotate(Vector3.right * Time.deltaTime * 10);
}
but how can I change this so that the next set position comes 10 milliseconds later?
Answer by tanoshimi · Dec 13, 2014 at 08:02 PM
Place your periodic code in a separate function and then call it using InvokeRepeating.
void Start() {
InvokeRepeating("myPeriodicMethod", 0, 0.01f);
}
InvokeRepeating should work or you could also record the Time.time so set a float RecordedTime then when the rotate starts so
RecordedTime = Time.time;
when you start your method and check if
(Time.time > RecordedTime + 0.01f)
In Update.
@tanoshimi: On most platforms which have vsync on your example would not run at 100 fps. InvokeRepeating can at max invoke one per frame. Unity only uses one thread for all scripting and it's the main thread, You can't do anything faster than your current fps. FixedUpdate is actually tied to the same limitation. However FixedUpdate is simply "fixed" by calling it multiple times in a row if necessary to keep the calling rate on average constant.
I've written a simple helper class that allows you to run as many FixedUpdate-like callbacks you want. You can specify any callrate (even 1000 times a second or once in 24h ^^): CustomFixedUpdate. $$anonymous$$eep in $$anonymous$$d that FixedUpdate doesn't make things any smoother. It's actually the opposite. If you want something to be visually smooth, do it in Update with the current FPS.
Would using CoRoutines/yield be considered bad style for this problem?
public class test : $$anonymous$$onoBehaviour
{
int i = 0;
const int ArraySize = 5;
int[] posArray = new int[ArraySize ] {2, 4, 6, 8, 10};
void Start()
{
StopCoroutine ("$$anonymous$$yCoRoutine");
StartCoroutine ("$$anonymous$$yCoRoutine", posArray [0]);
}
IEnumerator $$anonymous$$yCoRoutine(int targetPos)
{
while ( i < ArraySize )
{
// Read/$$anonymous$$odify
Vector3 pos = transform.position;
pos.x = $$anonymous$$athf.RoundToInt(gameObject.transform.position.x) + posArray [ i % ArraySize];
pos.y = $$anonymous$$athf.RoundToInt(gameObject.transform.position.y);
pos.z = $$anonymous$$athf.RoundToInt(gameObject.transform.position.z);
// Write
transform.position = pos;
// transform.forward //.localposition
// transform.Translate(Vector3.forward ...
// transform.AddTorque(Vector3.up ...
// transform.Rotate(Vector3.right ...
// transform.position = Vector3.Lerp ( ...
yield return new WaitForSeconds(0.1f);
}
// Wait for next 'Update(); ??
yield return null;
}