Hi .. I have that code : Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityEngine.Audio; public class HazardCollisionFunction : MonoBehaviour { #region Variables //Public public AudioSource effects; //Private private UIFunctions uiFunctions; public ParticleSystem hazardDustParticles; #endregion #region UnityFunctions void Start() { uiFunctions = GameObject.FindGameObjectWithTag("GameManager").GetComponent<UIFunctions>(); effects = GetComponent<AudioSource>(); } void Update() { } #endregion private void OnCollisionEnter(Collision collision) { if(collision.gameObject.tag == "Platform") { Destroy(Instantiate(hazardDustParticles.gameObject, transform.position, Quaternion.identity), hazardDustParticles.startLifetime); effects.Play(); Die(); } if (collision.gameObject.tag == "Player") { effects.Play(); uiFunctions.GameEnded(); } } public void Die() { Destroy(gameObject); } } Annd when my object hit the platform , the sound don't start , but when hit the player sound start , if i delete die on collision with platform , sound work , but my object doesn t destroy.. Sorry for my bad english
It's because you're destroying the AudioSource when you call Die(). Try this: Code (CSharp): if(collision.gameObject.tag == "Platform") { Destroy(Instantiate(hazardDustParticles.gameObject, transform.position, Quaternion.identity), hazardDustParticles.startLifetime); effects.transform.SetParent(null); effects.Play(); Die(); GameObject.Destroy(effects, 5f); } This removes the AudioSource from the game object, so that the audio source doesn't get destroyed when you call Die. Then the AudioSource will be destroyed 5 seconds later.
I put the sound collision on platform , and when game object hit platform , sound is activated Thank's you !
Fair enough. Just keep it in the back of your mind for later that if you want some sound to play when an object is destroyed, the AudioSource can't remain on the destroyed object, it will stop playing immediately. It's pretty common for objects to play a sound when destroyed, so the approach of un-parenting the audio source before playing it is common and works well.
There's also a function made just for that, https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html, the only drawback is that you can't set any of the audio source parameters like the audio mixer group or pitch, but this function is easy to reproduce, I've explained how I did that and a little more on my blog https://bladecast.pro/unity-tutorials/how-to-play-sound-collision-even-destroy