- Home /
Audio and Particles on Trigger
I have been working on this powerup for sometime and every time I think I have it perfected a new issue appears. My latest issue involves the instantiated sounds and particles when a trigger occurs between the player and the powerup. I have tried many different fixes, but I can't seem to progress. Right now when the player collides with the powerup the sound does not play, the particle system triggers, but is never destroyed, and if I pass through the area where the spawned powerup appears the particles are triggered again. I think the particles continue to trigger because the collider that is attached to the powerup is still active. I tried to disable this and it works, but the sound will not play and on some of my other powerups the particles never trigger. What can I edit or add in my code to get the sound to play and the particles to destroy? This is really frustrating because I have the same particle and audio code attached to other gameobjects (ontrigger) and it works fine, but the difference is that I do not destroy the powerup right away (due to the coroutine and duration of the effect) as opposed to my other gamobjects that I destroy on trigger. I am so close!
Here's my code:
using UnityEngine;
using System.Collections;
public class Multiplier : MonoBehaviour {
public GameObject particle;
public AudioClip powerUpSound;
public float time;
bool Active=false;
//public static bool particleActive=false;
void Update(){
/*if (particleActive == true) {
Destroy (particle, 1.2f);
}*/
if (Active==false) {
StartCoroutine (DestroyGameObject ());
}
}
IEnumerator ScoreMultiplier(){
//gameObject.GetComponent <BoxCollider2D > ().enabled = false;
Active = true;
ScoreManager .multiplier ++;
yield return new WaitForSeconds (time);
ScoreManager.multiplier--;
Destroy (gameObject);
}
IEnumerator DestroyGameObject(){
yield return new WaitForSeconds (3);
gameObject.GetComponent <SpriteRenderer > ().enabled = false;
yield return new WaitForSeconds (20);
Destroy (gameObject);
}
void OnTriggerEnter2D(Collider2D other){
if (other.tag == "Player") {
//particleActive = true;
Active = true;
GameObject clonedParticle;
clonedParticle =Instantiate (particle, transform.position, transform.rotation) as GameObject ;
GameObject sound = new GameObject();
sound.transform.position = transform.position;
AudioSource audioSource = sound.AddComponent<AudioSource>();
audioSource.clip = powerUpSound;
audioSource.Play();
Destroy (clonedParticle,1.2f);
Destroy (powerUpSound, powerUpSound.length);
Destroy (sound);
gameObject.GetComponent <SpriteRenderer > ().enabled = false;
StartCoroutine (ScoreMultiplier ());
//Destroy (gameObject);
}
}
}