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();
}
}
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.