I am trying to create a game-object that increases a counter and plays a sound on being triggered and then being destroyed. Think of it like the Coins in Mario and alike.
I do have my Script for the object which at the current state, increases the counter (Clartiy) just once, plays the sound, then turns the object invisible. Planned was that a second collision destroys it without doing anything else, though that part fails and it actually plays the sound again.
void OnTriggerEnter(Collider c)
{
if (c.gameObject.tag == "Player" && firstCol)
{
Debug.Log("firstCol=" + firstCol);
audio.PlayOneShot(gong, 1.8f);
Player.GetComponent<Player>().Clarity += 1;
renderer.enabled = false;
firstCol = false;
Debug.Log("firstCol=" + firstCol);
}
if (c.gameObject.tag == "Player" && !firstCol)
{
Debug.Log("firstCol=" + firstCol);
Debug.Log("PreDestro");
WaitForDestro();
// tried "Destroy(gameObject);" here too, didn't work
}
}
private IEnumerator WaitForDestro() {
yield return new WaitForSeconds(0.1f);
Debug.Log("WaitForDestro Done");
Destroy (gameObject);
}
firstCol is initialized as true since the first Collision is supposed to run the first if-statement. The Delay through the coroutine is there because otherwise it seems to instantly destroy the object, giving me the “Can’t play a disabled audio source” problem.
as for the firstCol Debug-log, what I get there is:
firstCol=true
fristCol=false
fristCol=false
ProDestro
from walking through it once.
walking through again gives me
fristCol=false
ProDestro
nothing else, the “WaitforDestro Done” doesn’t appear either.
I also tried to work with OnTriggerExit, but that didn’t solve the problem as well.
Anyone know what’s wrong with my Code/Approach and if there’s a better way?