Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Question - Sound Collider

Discussion in 'Scripting' started by kholyphoenix1, Nov 16, 2015.

  1. kholyphoenix1

    kholyphoenix1

    Joined:
    Apr 17, 2015
    Posts:
    57
    Hello,

    I found this code in Unity guide.
    He works.
    When I collide with the object it is destroyed no more runs the sound.

    Script:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class BlockDestroy : MonoBehaviour {
    5.  
    6.     void Update() {
    7.  
    8.     }
    9.  
    10.     void OnCollisionEnter (Collision collision) {
    11.  
    12.         // Destruir BlockObject
    13.         GameObject[] objectsToDestroy = GameObject.FindGameObjectsWithTag("BlockObject");
    14.             foreach (GameObject go in objectsToDestroy)
    15.             {
    16.             Destroy(go);
    17.             }
    18.  
    19.             // Destruir Este Objeto
    20.             Destroy(this.gameObject);
    21.  
    22.     }
    23.  
    24. }
    Manual:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. // [RequireComponent(typeof(AudioSource))]
    5. public class ExampleClass : MonoBehaviour {
    6.     public AudioClip impact;
    7.     AudioSource audio;
    8.  
    9.     void Start() {
    10.         audio = GetComponent<AudioSource>();
    11.     }
    12.  
    13.     void OnCollisionEnter() {
    14.         audio.PlayOneShot(impact, 0.7F);
    15.     }
    16. }
     
    Last edited: Nov 16, 2015
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    destroy used like that removes the gameobject and everything attached to it, including the audiosource.

    either:

    use destroy(thing, timetowait) version of the function, this will destroy the thing after the timetowait amount of time letting the sound play out

    or

    play the sound on another gameobject which isn't being destroyed
    (possibly using http://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html)
     
  3. kholyphoenix1

    kholyphoenix1

    Joined:
    Apr 17, 2015
    Posts:
    57