Search Unity

Audio How to Assign Audio to Specific Area of Map?

Discussion in 'Audio & Video' started by JonathanGentile1, Sep 12, 2018.

  1. JonathanGentile1

    JonathanGentile1

    Joined:
    May 2, 2018
    Posts:
    7
    Hello,

    I have a level in a 2D platformer game that I want to have a few audio transitions. The top part of the map I want to have 1 song play as soon as the player enters the level. There's a long section where the user falls and I don't want there to play any audio. Then in the final room I want a totally different song to play. I was aware that the min distance and area affected where the audio would be played. However when I have both audio objects in place and with their specific area, both songs play at the same time.
     

    Attached Files:

  2. Docaroo

    Docaroo

    Joined:
    Nov 7, 2017
    Posts:
    82
    You can technically do this with 3D audio sounds and set the curves and distances properly ... perhaps like this:

    upload_2018-9-13_10-43-58.png


    But that's not how I would handle this here ... I would do this by just triggering the audiosource.play based on the events of the level (player falling = stop first audio and play next audio). Since there's a silent gap between the two musics this is perfectly fine.
     

    Attached Files:

    JonathanGentile1 likes this.
  3. JonathanGentile1

    JonathanGentile1

    Joined:
    May 2, 2018
    Posts:
    7
    Thank you very much, but I ended up writing a script:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3.  
    4.  
    5.  
    6. public class SoundOff : MonoBehaviour {
    7.  
    8.     public AudioClip nextMusic; // drag the next music here in the Inspector
    9.     public AudioSource audioObject; // drag the music player here or...
    10.  
    11.     void Start()
    12.     { // find it at Start:
    13.       // supposing that the music player is named "MusicPlayer":
    14.         audioObject = gameObject.GetComponent<AudioSource>();
    15.     }
    16.  
    17.     void OnTriggerEnter2D(Collider2D other)
    18.     {
    19.         if (other.tag == "Player")
    20.         { // only an object tagged Player stops the sound
    21.             audioObject.Stop();
    22.             Debug.Log("Player entered!");
    23.         }
    24.     }
    25.  
    26.     void OnTriggerExit2D(Collider2D other)
    27.         //use ontriggerexit 2D instead of no 2D because of collider
    28.    
    29.     {
    30.         if (other.tag == "Player")
    31.         { // only an object tagged Player restarts the sound
    32.             audioObject.clip = nextMusic;  // select the next music
    33.             audioObject.Play(); // play it
    34.             Debug.Log("Player exit!");
    35.         }
    36.     }
    37. }
     
  4. Docaroo

    Docaroo

    Joined:
    Nov 7, 2017
    Posts:
    82
    That's basically what my second suggestion was :)