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

code to trigger audio file on collision

Discussion in 'Scripting' started by Patrk, Jun 18, 2017.

  1. Patrk

    Patrk

    Joined:
    Apr 9, 2017
    Posts:
    48
    I want to trigger an audio file with a simple collision with an object.
    The object has a box collider attached and an audio source component attached also.
    The object is called ‘cube’ the audio file called ‘sound’.

    Whats the simplest code that I can attach as a script component to the object to trigger the audio file when the FPS walks into it?
     
  2. Rick-Gamez

    Rick-Gamez

    Joined:
    Mar 23, 2015
    Posts:
    218
    Code (csharp):
    1.  
    2. public class SomeScript : MonoBehaviour{
    3.     public AudioSource source;
    4.  
    5.     void Start(){
    6. //if this script is not attatched to cube then find the Game Object otherwise this.gameObject can replace go
    7.         var go = GameObject.Find("Cube");
    8.         if(go != null){
    9.             source = go.GetComponent<AudioSource>();
    10.         }
    11.     }
    12.  
    13.     void OnCollisionEnter(Collider other){
    14.         if(source != null && !source.isPlaying){
    15.             source.Play();
    16.         }
    17.     }
    18. }
    19.  
     
    Last edited: Jun 18, 2017
  3. Patrk

    Patrk

    Joined:
    Apr 9, 2017
    Posts:
    48
    Hi many thanks,

    I ticked the box collider component as trigger and changed the code to -
    void OnTriggerEnter(Collider other)

    works great!
     
  4. Rick-Gamez

    Rick-Gamez

    Joined:
    Mar 23, 2015
    Posts:
    218
    Yes if you are using a trigger collider then OnTriggerEnter is the way to go! Good work!