c# sound in unity 5
when i run this code i made that is supposed to play music it will play the same song overlapping itself. i know its because it is in the void update and not void start but i want the script to check if the player is alive.
I've been struggling to find any helpful videos on c# sound with the new unity 5 audio settings and code stuffs. after all the looking about i have managed to get some music to play if my character is alive(if he dies i want to change the music to some sad music or something later but i would already know how to do that if i knew how sound worked)
basically i'm completely bamboozled when it comes to audio in unity 5.
i know its probably reeealy simple but i basically know nothing about coding except the bare bone basics.
how would i go about looping the audio? like making the script wait audio is done playing before it playing it again in the next tick?
using UnityEngine; using System.Collections;
public class music : MonoBehaviour { public AudioClip sanic; private AudioSource source;
// Use this for initialization
void Awake () {
source = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
if (health.alive == true) {
source.PlayOneShot (sanic, 1f);
}
}
}
Answer by hexagonius · Dec 03, 2016 at 07:36 AM
A OneShot is a "play it and leave it" method, not giving you any info on the audio clip time, play position etc. It should be used for short audio files like, well, shots (short and forgettable).
For music however you should be setting the audioclip up in the AudioSource directly und just call Play() on it or configure it as play on awake. checking the loop checkbox gets rid of repeating the audio file manually. All you have to do now is check for the moment the player died to swap the audio clip out. So what you can do if you've done everything above is:
public AudioClip deathClip;
// Use this for initialization
void Awake () {
source = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
if (!health.alive) {
source.clip = deathClip;
enabled = false;
}
}
It checks for the player if he is dead every time and if he is (using ! is like checking heath.alive == false), it changes the audioclip and disables this script, so the update loop does not run anymore
this was extremely helpful lol I've been stumped for three days now