I’m having trouble calling a function at the correct time while looping. Either it calls it too fast or too slow. I thought I figured it out yesterday, but I didn’t… Here is a diagram to show what I’m trying to do, I know I have some logic issue going on.
In Update() I call a function called blinkAtRandom();
This function has a timer that goes off X amount of time.
When this timer goes off, it calls BlinkOnce();.
BlinkOnce() will change the texture for the eye animation, but only 1 texture per Y amount of time, so I want to loop through this eyelidTextures.Length amount of loops
The problem now, is looping ignores the timers so my results are either too “fast” (blink never can become false) or too “slow” (only changes 1 texture through an entire loop, and blink is always true).
Here is a sample of my code. I also want to point out if you stick BlinkOnce() by itself in update, it changes at the correct time and looks like Ideal Timing, so it works, it just can’t be called from another function or I get the timing issues.
int BlinkOnce(float resetTime)
{
if (blink)
{
myTimer.x -= Time.deltaTime;
//timer finished
if (myTimer.x <= 0)
{
//StartCoroutine("OneBlink");
OneBlinkF();
myTimer.x = resetTime;
eyeFrame += 1;
}
//go through all of blink frames
if (eyeFrame > eyelidTextures.Length)
{
//stop blinking
blink = false;
eyeFrame = 0;
}
}
return 1;
}
Here is my other function
void blinkAtRandom()
{
myTimer2 -= Time.deltaTime;
if (myTimer2 <= 0)
{
//blink = true;
for (int i = 0; i < eyelidTextures.Length; i++)
{
BlinkOnce(myTimer.y);
}
//reset timer
myTimer2 = Random.Range(eyeBlinkRange.x, eyeBlinkRange.y);
}
}
Both samples of code have been altered a great deal so they only show 1 of many test cases I’ve tried.
This really should be easy, so I don’t know how I ended up making this so complicated!
_Gkxd
2
The piece of code below will print “A” once every half second. You might find it useful.
public void Start() {
StartCoroutine(DoSomethingEveryHalfSecond());
}
private IEnumerator DoSomethingEveryHalfSecond() {
while (true) {
Debug.Log("A");
yield return new WaitForSeconds(0.5f);
}
}
Are you sure this is not because you are doing this in Update()? Update is not guarenteed to be called at fixed intervals, and could be contributing to the problem.
Try moving the code to FixedUpdate(), and see if it improves.
Also, _Gkxd’s method would work.