In this recipe, we take care of instantiating a particle system prefab in the place of a collected item that disappears, and also use the particle system to play the sound effect we set for this specific game event.
To achieve this, we need a new script and need to make some modifications to the Runner script, so let's begin.
Update()
function so that it contains the following lines. They tell the PS to destroy itself once the audio attached to it has finished playing:void Update () { if(!audio.isPlaying){ Destroy(this.gameObject); } }
public GameObject ps;
if()
statement inside the OnCollisionEnter()
function. It takes care of creating the PS in the place of the collectible, which can then be destroyed:Instantiate(ps, c.transform.position, Quaternion.identity);
OnCollisionEnter()
function of the Runner script:void OnCollisionEnter(Collision c){ if(c.gameObject.tag == "platform"){ bIsTouch = true; charAnimator.SetBool("bJump",false); } if(c.gameObject.tag == "collectible"){ Instantiate(ps, c.transform.position, Quaternion.identity); GameObject.Destroy(c.gameObject); collected += 1; } }
ps
public variable.You can refer to the following screenshot that shows the operation we just described:
Using the particle system, we solved our problem of playing an audio clip on a game object that is about to be destroyed. Instead of putting the audio clip in the collectible item, we put it in a particle system prefab that we instantiate in the scene whenever a collectible is gathered by the player.
At the same time, we provide clear, consistent feedback to the player that they achieve something good when the character hits a collectible.
3.139.105.159