How to Get a Program That Was Playing Sound to Play Sound Again
I piece of work in Unity a lot and, while I'm e'er learning, it'south easy to forget that, for a lot of people using the software for the first fourth dimension, the most useful techniques to know are oft the virtually basic ones.
Once y'all know the nuts it's much easier to learn more, to experiment and to develop more advanced ideas. Then, to help, I've decided to put together an easy guide that covers the basics of playing audio and sounds in Unity, along with some existent examples that you lot tin utilise in your project.
And then… How do you play audio in Unity?
In that location are several different methods for playing audio in Unity, including:
- audioSource.Play to start a single clip from a script.
- audioSource.PlayOneShot to play overlapping, repeating and not-looping sounds.
- AudioSource.PlayClipAtPoint to play a prune at a 3D position, without an Sound Source.
- audioSource.PlayDelayed or audioSource.Playscheduled to play a clip at a time in the future.
- Or by selecting Play on Awake on an Sound Source to play a clip automatically when an object loads.
Each method has its own unique benefits and use cases and in this article I'll be explaining how each one works in item as well as providing some examples that y'all tin can utilise in your game.
What y'all'll notice on this page
Methods for playing audio and sounds in Unity
- How to use Play
- How to utilise Play I Shot
- How to apply Play Prune at Betoken
- How to utilise PlayDelayed and Play Scheduled
- How to utilize Play on Awake
- Ready-made options
Useful examples of audio triggers
- How to play a random sound
- How to play a repeating sound
- How to play a audio when pressing a button
- How to start music or audio when entering an expanse (3D & 2nd)
- How to play a sound when colliding with an object (3D & 2D)
- How to play a sound when destroying an object
How to play audio in Unity
Here's a quick overview of the five different methods and how they work.
How to use Play
//Plays an Audio Source audioSource.Play();
Phone call Play from a script to start an Audio Source:
public class PlayAudio : MonoBehaviour { public AudioSource audioSource; void Start() { audioSource.Play(); } }
Calling Play will trigger whatsoever Audio Clip is attack the Audio Source. It'southward the nigh common method of triggering audio and is well-nigh suitable for playing looping sounds and music.
This is considering some other methods, such as Play Ane Shot, cannot trigger looping sounds, and also because using Play will but allow i prune to be played at a time from that Audio Source.
Calling Play on an Sound Source that is already playing will end the Sound Source and offset the clip over again.
How to use Play One Shot
//Plays a specific clip on an Audio Source once audioSource.PlayOneShot(AudioClip audioClip, Bladder volumeScale);
Play One Shot is perchance the bottom-known method of triggering a audio on an Audio Source but is extremely useful for triggering sound effects.
public grade PlayAudio : MonoBehaviour { public AudioSource audioSource; public AudioClip clip; public bladder volume=0.5f; void Get-go() { audioSource.PlayOneShot(clip, volume); } }
Play One Shot is chosen on the Audio Source and takes a parameter for the Sound Clip to play. This means that yous must specify what prune you would like to play when you call PlayOneShot.
If, even so, yous just want to play whatsoever prune is on the Audio Source (similar you would with play) so you tin simply laissez passer a reference to that prune like this:
audioSource.PlayOneShot(audioSource.prune, volume);
You tin can also set an optional volume calibration when calling Play 1 Shot. This takes a bladder value between 0 and i and will adjust the volume of the prune relative to the book of the Audio Source.
This is bully for variation considering information technology means that y'all can pass in a randomised book value, or play two different clips at different volumes, without irresolute the overall volume of the Audio Source itself.
Play One Shot is ideal for sound effects, particularly repeating sounds (for example gunfire). Triggering Play One Shot on an Sound Source that's already playing volition overlap the sounds (instead of interrupting information technology, similar it would with Play).
This makes Play One Shot especially suitable for repeating sounds simply be conscientious. Attempt not to permit too many sounds to overlap all at once.
Despite only playing from ane Audio Source, two sounds triggered via Play One Shot will count as two 'voices'. And even though the maximum voice limit tin can be increased from the default 32 voices, dissimilar platforms have different limitations, so it's good practice to endeavour to keep the total voice count as low as possible to avert sounds being culled.
- Observe out more nigh Play One Shot
How to use Play Clip At Betoken
//Plays a clip in one case at a specific position, without an Audio Source AudioSource.PlayClipAtPoint(AudioClip prune, Vector3 playPosition, Float volume);
Play Clip at Indicate works in a similar way to Play One Shot with 1 large difference. It doesn't require an Audio Source to piece of work.
This is great for one-off sounds equally you won't need to add together an Audio Source component to an object, you tin just burn down a audio in one case, from a specified position in the Scene, without any fuss.
public class PlayAudio : MonoBehaviour { public AudioClip clip; public float volume=1; void Start() { AudioSource.PlayClipAtPoint(prune, transform.position, book); } }
Note the majuscule A in 'AudioSource', as Play Clip at Indicate uses the Audio Source grade, instead of an instance of an Audio Source.
You besides have to pass in a position that the Audio Prune volition play from. In this example I've used the position of the object that this script is attached to.
So how does this work exactly?
Behind the scenes, Unity creates a new, temporary Audio Source to play the clip from and disposes of it once the prune is finished. In the editor, yous'll see a new Game Object announced and disappear when this happens. This makes Play Clip at Point especially useful when using an Audio Source Component isn't an option.
For example, when playing a audio when an object is destroyed.
If the Audio Source is on the object that's existence destroyed the sound will ordinarily exist cut off, or it may never go a chance to commencement, equally the Audio Source now longer exists.
Using Play Clip at Point instead allows the sound to continue after the object is destroyed via a temporary Sound Source that is neatly disposed of one time the audio is finished.
However, in that location is a take hold of…
The downside of using Play Prune at Point
Because the Sound Source that the clip is played from is created at run time, you don't get the selection to change any of the Audio Source's settings. The Audio Source is created using default settings, with the exception of spatial blend which will be set to fully 3D.
This too means that you can't apply Play Clip at Bespeak with an Audio Mixer. The output volition go directly to the Audio Listener, equally information technology does by default.
If you do need to change any of the Sound Source's settings there are ways yous can become effectually this (by creating your own modified version of the Play Clip at Point functionality). However, in that scenario, information technology's probably going to be much, much easier to simply use a regular Sound Source.
How to apply Play Delayed and Play Scheduled
Play Delayed and Play Scheduled allow you to play an Sound Source in the future, in two dissimilar means.
Play Delayed
//Plays an Audio Source subsequently a delay AudioSource.PlayDelayed(bladder delay);
The first, Play Delayed, takes a delay in seconds and is the simplest method for delaying an Audio Prune.
public class PlayAudio : MonoBehaviour { public AudioSource audioSource; public float filibuster=4; void Showtime() { // Plays an Audio Prune subsequently 4 seconds audioSource.PlayDelayed(filibuster); } }
This method is piece of cake to use and is ideal for apace irresolute the timing of an Audio Source.
Examples of when you would use this include delaying the start of music, audio effects that occur later the event that triggers them, like lightning and thunder for example, and other timing tweaks and randomisations.
Play Delayed is dandy for elementary timing, merely it is not suitable for more precise timekeeping, like stitching two clips together or beat matching audio clips.
For that, you need PlayScheduled.
Play Scheduled
//Plays an Audio Source at a precise time AudioSource.PlayScheduled(double timeToPlay);
Play Scheduled works a trivial differently to Play Delayed, but it'southward incredibly precise.
This is due to the fact that it operates using the actual sound engine time and takes a highly accurate double value, instead of a float.
To apply it, you demand to specify the time the Audio Source should start, not a delay. This corresponds to the AudioSettings.dspTime, which is the number of seconds the sound engine has been running.
Play Scheduled is ideal for precise audio timing tasks, similar queueing audio clips to play exactly after ane another, or for vanquish matching.
The beneath example hows how to queue a clip to play seamlessly later on another clip has finished.
public class PlayAudio : MonoBehaviour { public AudioSource audioSource1; public AudioSource audioSource2; void Start() { audioSource1.PlayScheduled(AudioSettings.dspTime); double clipLength = audioSource1.prune.samples / audioSource1.clip.frequency; audioSource2.PlayScheduled(AudioSettings.dspTime + clipLength); }
There'southward a lot that y'all can practice with PlayScheduled. So much that I wrote a huge guide on but that, with examples of how to queue upward clips, beat match audio and how to end loops with musical stings.
- How to queue audio clips in Unity: The ultimate guide to Play Scheduled
Using isPlaying when scheduling audio won't work
When scheduling sound using either method, the Audio Source is considered to exist playing as before long as it is scheduled and until later it has finished. This happens as soon as the Audio Source is queued, not when the audio starts, so isPlaying will be true, fifty-fifty if no sound is being made nevertheless.
This means that, when scheduling audio, you cannot check if the audio has started or stopped using isPlaying.
How to utilize Play on Awake
Play on awake is the easiest way to trigger a sound, every bit information technology requires no scripting whatsoever.
Enabled by default, Play on Awake volition kickoff the Audio Source as soon equally the object is enabled. This will commonly be the commencement of the scene if the Game Object is already enabled or, if it is disabled, Play on Awake volition fire as shortly equally the Game Object, or the Audio Source, becomes active.
This is useful for automatically starting audio when an object loads, such as music at the first of a scene or a sound that plays when an object is initialised.
For example, to add together a audio when a new object is created, simply add an Audio Source component to the prefab of that object and make sure Play on Awake is checked. And so, when the object is added to the Scene, the sound volition play.
For more data on the different methods that can be called from an Audio Source, try Unity's official documentation.
Prepare-made options
While Unity's built-in options for handling audio are much better than they used to be, if you desire easy access to avant-garde audio features (or even if you simply want to relieve some fourth dimension) you might want to consider an audio managing director plugin from the Unity Asset Store.
Chief Sound, for case, has long been the gold standard in audio manager assets. Fully featured and well supported, it offers advanced features, such as audio occlusion, as well as bones conveniences, such equally solutions for adding sounds to odd-shaped objects (such as rivers for example). The Multiplayer version extends the nugget farther, making, normally challenging, multiplayer audio, much easier.
For larger developers, Fmod and Wwise are powerful audio integration options, both of which are uniform with Unity (Fmod has a Unity plugin which yous tin download from the Nugget Store here). While powerful, their advanced features are offered under licensing tiers which are, much like Unity, based on revenue and product budget. For more than, cheque the official websites here: Fmod, Wwise.
Audio trigger examples
Now y'all know the unlike methods for triggering audio in Unity it's time to put them to work.
Below you lot'll find some examples of common audio triggers that you can re-create and paste in to your project.
How to play a random audio
What's the all-time way to select a random sound in Unity?
Showtime, create an Audio Source and an assortment of Audio Clips.
public AudioSource audioSource; public AudioClip[] audioClipArray;
Back in Unity, add the different Audio Clips to the Array.
Adjacent, write a function, with an Audio Clip return type, to select one of the clips at random.
AudioClip RandomClip(){ return audioClipArray[Random.Range(0, audioClipArray.Length)]; }
And so whenever you want to use a random Audio Clip, pass in the part where you would usually pass in the clip name:
void Start() { audioSource.PlayOneShot(RandomClip()); }
How to trigger a random sound, with no repeats
To prevent the same sound triggering twice in a row, store the previous audio in a variable and check against information technology with a while statement, like this:
public form PlayAudio : MonoBehaviour { public AudioSource audioSource; public AudioClip[] audioClipArray; AudioClip lastClip; void Beginning() { audioSource.PlayOneShot(RandomClip()); } AudioClip RandomClip() { int attempts = 3; AudioClip newClip = audioClipArray[Random.Range(0, audioClipArray.Length)]; while (newClip == lastClip && attempts > 0) { newClip = audioClipArray[Random.Range(0, audioClipArray.Length)]; attempts--; } lastClip = newClip; return newClip; } }
How to play a repeating sound
Here'due south an case of how to trigger a sound repeatedly in Unity, in this case for a machine gun that fires every 0.25 seconds.
I'chiliad also using the Audio Clip array from the last example to apply a random audio every fourth dimension the gun is fired.
public form PlayAudio : MonoBehaviour { public AudioSource audioSource; public AudioClip[] audioClipArray; public float timeBetweenShots = 0.25f; float timer; void Update() { timer += Time.deltaTime; if (timer > timeBetweenShots) { audioSource.PlayOneShot(RandomClip()); timer = 0; } } AudioClip RandomClip() { return audioClipArray[Random.Range(0, audioClipArray.Length-1)]; } }
How to play a audio when pressing a push button
Unity has a built in method for triggering events when a button is pressed and this includes an option for playing an Sound Clip.
Merely create an On Click event trigger, drag a Game Object to the object field and select PlayOneShot(AudioClip) from the Sound Source section of the drop downwardly carte.
Once you've selected Play I Shot, select an Audio Prune to play in the new field that appears.
By using Play One Shot, it'due south possible to take different buttons play dissimilar sounds using only a single Audio Source.
However, y'all can likewise select from Play, or PlayDelayed, but like when playing from a script.
How to beginning music when entering an area (3D & 2D)
How can you create a music trigger in Unity that fires when the player enters a specific area?
Commencement create the Trigger:
- Create a shape, such as a cube that will act as the trigger area in the scene.
- Remove the mesh renderer if there is i, you won't demand it for this.
- On the Collider component make certain Is Trigger is gear up to true.
- If the Role player object doesn't have 1 already, you'll need to add together a Rigidbody component for this to piece of work.
- Finally, on the Role player object, select the Player Tag.
Adjacent, add this script to the trigger area:
public class PlayOnCollision : MonoBehaviour { public AudioSource audioSource; void OnTriggerEnter(Collider other) { if (other.tag == "Player" && !audioSource.isPlaying) { audioSource.Play(); } } }
How to create a trigger audio in second
To create the aforementioned effect in a 2D project, simply use the 2d Collider and second Rigidbody, making sure to update the script to match:
void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player" && !audioSource.isPlaying) { audioSource.Play(); } }
How to play a audio when colliding with an object (3D & second)
Only like inbound an area, y'all tin trigger a sound when ii objects collide, for example if an object falls on the ground.
Likewise like entering an area, the object will need to have a Rigidbody component for this to work.
Place this script on the moving object:
public class PlayOnCollision : MonoBehaviour { public AudioSource audioSource; void OnCollisionEnter(Collision standoff) { audioSource.Play(); } }
To preclude minor collisions triggering the sound, it's possible to only play the audio for larger collisions, past checking the velocity of the collision:
public course PlayOnCollision : MonoBehaviour { public AudioSource audioSource; void OnCollisionEnter(Standoff standoff) { if(collision.relativeVelocity.magnitude > 1) audioSource.Play(); } }
Or, for a more natural sounding collision, you tin can vary the volume based on the force of the standoff.
public grade PlayOnCollision : MonoBehaviour { public AudioSource audioSource; public float maxForce = 5; void OnCollisionEnter(Standoff collision) { float force = collision.relativeVelocity.magnitude; float book = 1; if (forcefulness <= maxForce) { volume = force / maxForce; } audioSource.PlayOneShot(audioSource.clip, volume); } }
The max volume value decides what force of touch will produce the loudest sound. A value that exceeds the max strength will simply play at total volume.
How to create a collision sound in 2D
The same method tin can be used to create a collision sound effect in a 2d game using 2D Colliders, a 2D Rigidbody and updating the script classes to match, similar this:
void OnCollisionEnter2D(Collision2D collision) { audioSource.Play(); }
How to play a sound when destroying an object
To play a sound that continues after an object has been destroyed, i selection is to use Play Clip at Point, like this:
public class PlayOnDestroy : MonoBehaviour { public AudioClip audioClip; void DestroyObject() { AudioSource.PlayClipAtPoint(audioClip, transform.position); Destroy(gameObject); } }
This works past creating a temporary Audio Source that plays at the object's final position, even though the original object is gone.
Now I'd like to hear from you…
Hopefully, these tips and examples will help you lot play sound in Unity more easily.
At the very least yous now know many of the basic options available for playing audio in Unity, making information technology easier to build more circuitous audio systems.
But now I desire to hear from you lot…
How will yous use these examples in your game? Or maybe your project needs something dissimilar, that's not in this article. What challenges did y'all face when starting with the basics of audio in Unity?
Let me know by leaving a comment below.
My favourite time-saving Unity assets
Rewired (the best input management organization)
Rewired is an input management asset that extends Unity's default input system, the Input Manager, calculation much needed improvements and support for modern devices. Put merely, information technology's much more advanced than the default Input Director and more reliable than Unity's new Input Organization. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, and then I tin can understand why everyone loves it.
DOTween Pro (should exist congenital into Unity)
An asset and so useful, it should already exist congenital into Unity. Except information technology's non. DOTween Pro is an blitheness and timing tool that allows yous to animate anything in Unity. You tin can move, fade, scale, rotate without writing Coroutines or Lerp functions.
Easy Save (there'south no reason non to use it)
Piece of cake Save makes managing game saves and file serialization extremely easy in Unity. Then much and then that, for the time information technology would take to build a salve arrangement, vs the cost of buying Easy Salve, I don't recommend making your own salvage system since Like shooting fish in a barrel Salvage already exists.
Source: https://gamedevbeginner.com/how-to-play-audio-in-unity-with-examples/
0 Response to "How to Get a Program That Was Playing Sound to Play Sound Again"
Post a Comment