I am trying to limit only one instance of async function running in a colliderhit event. I learned that I can use an async lock. I adopted the code as below but the async function still run multiple times.
private static SemaphoreSlim _sl = new SemaphoreSlim(1, 1);
async Task Break2(GameObject obj2break){
await _sl.WaitAsync();
try {
await Task.Delay(1000);
audioSource.Play();
obj2break.SetActive(false);
Instantiate(brokenObject, obj2break.transform.position, obj2break.transform.rotation);
Vector3 explosionPos = obj2break.transform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPos, radius);
foreach (Collider hit in colliders)
{
if (hit.GetComponent<Rigidbody>())
{
hit.GetComponent<Rigidbody>().AddExplosionForce(power, explosionPos, radius, upwards);
}
}
} finally
{
// Release the thread
_sl.Release();
}
}
Thanks in advance for any help!