- Home /
How to call a function every x frames?
Hello,
I am working on the background music of my game and I want to play an audio clip every 11 frames only if I am hitting a special collider, however on my current script, this seems not to be working, how can I fix this? (here is my code:)
private int interval = 11;
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "BoucleUneEtMelodieUne" && Time.frameCount % interval == 0)
{
PlayBoucleUneEtMelodieUne();
}
}
Answer by darksider2000 · May 13, 2020 at 08:19 PM
Hi,
OnTriggerEnter2D runs once when the object enters a trigger collider. So your if statement only runs once.
You can use OnTriggerStay2D which will run every physics frame (50 fps).
private int interval = 11;
void OnTriggerStay2D(Collider2D col)
{
if (col.gameObject.tag == "BoucleUneEtMelodieUne" && Time.frameCount % interval == 0)
{
PlayBoucleUneEtMelodieUne();
}
}
Or you can use a boolean to check if you're inside the trigger or not. Then you'd use OnTriggerEnter2D and OnTriggerExit2D to flip the boolean, and in your Update() or FixedUpdate() you'll be running the if statement along with the boolean:
private int interval = 11;
private bool insideTrigger = false;
void OnTriggerEnter2D(Collider2D col)
{
insideTrigger = true;
}
void OnTriggerExit2D(Collider2D col)
{
insideTrigger = false;
}
void FixedUpdate ()
{
if (col.gameObject.tag == "BoucleUneEtMelodieUne" &&
Time.frameCount % interval == 0 && insideTrigger)
{
PlayBoucleUneEtMelodieUne();
}
}
I'd suggest trying the former first.
Your answer
Follow this Question
Related Questions
Change Material depending on Collider position? 2 Answers
Why when i move the player object through the door the ontriggerenter/exit event are not fire ? 2 Answers
FPS all of a sudden gets stuck in floor??? 0 Answers
Connect 2 gameobjects to interact with them simultaneously? 2 Answers
How do you allow the joints in a character to freely fall based on gravity? 1 Answer