Simple Sound Manager (Unity Tutorial)

Let's learn how to play Sounds and create a simple Sound Manager class to handle playing any Sound we want in 2D and 3D.
GameAssets class video
• Quick Tip: Referencing...
If you have any questions post them in the comments and I'll do my best to answer them.
See you next time!
Grab the game bundle at unitycodemonkey.com/gameBundl...
Get the Code Monkey Utilities at unitycodemonkey.com/utils.php
#unity3d #tutorial #unity2d
--------------------------------------------------------------------
Hello and welcome, I am your Code Monkey and here you will learn everything about Game Development in Unity 2D using C#.
I've been developing games for several years with 7 published games on Steam and now I'm sharing my knowledge to help you on your own game development journey.
You can see my games at www.endlessloopstudios.com
--------------------------------------------------------------------
- Website: unitycodemonkey.com/
- Twitter: / unitycodemonkey
- Facebook: / unitycodemonkey

Пікірлер: 263

  • @CodeMonkeyUnity
    @CodeMonkeyUnity5 жыл бұрын

    Do you normally play your sounds through code or instantiate a prefab?

  • @morne914

    @morne914

    5 жыл бұрын

    I instantiate a prefab, it is much easier.

  • @rickloyd8208

    @rickloyd8208

    5 жыл бұрын

    You will not believe but I am forced to use asset bundles (since I have too much different audio files). Yesterday I used your logic to create a static, do not destroy-able object to load bundles asynchronously, extract assets and signal scene loader when everything is finished, so it can hide loading popup. To be honest everything became too complicated and I worry a lot about memory leak. Of course I unload bundles (with exception of used assets) but will be memory cleaned when AudioClip gets destroyed by moving to new scene? Code monkey, have you ever used asset bundles?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    @@rickloyd8208 I've never used Asset Bundles but the AudioClip should be cleaned up if there are no references to it at all so unloading the asset bundle and destroying the sound should work. You can verify using the Profiler, it shows you what assets are occupying what memory.

  • @foreignwarren7361

    @foreignwarren7361

    4 жыл бұрын

    through code...more fun

  • @insaneduane

    @insaneduane

    3 жыл бұрын

    Both. I'm into VR so directional/distance is important. Melee attacks are through code, but my ranged weapons raycast hit instantiates a prefab that parents a random prefab from its array at its hitpoint . The arrays contain different samples of the same type of sound (3 different "metal" sounds when it hits a "metal" tag, concrete, wood, etc.) and then destroys itself. I'm going to experiment with pooling the sounds for efficiency reasons.

  • @rickloyd8208
    @rickloyd82085 жыл бұрын

    I was doing almost the same with audio manager but I loved how you used enum for different sounds plus use that enum for sound array and finally function to search for audio clip or log error if you forgot to add it to asset manager. Thanks for awesome pattern!

  • @partyhardwithme
    @partyhardwithme4 жыл бұрын

    Just so you get an idea of how awesome this is, you are teaching people to build scripts that are paid assets in the store. Thank you so much for sharing your knowledge with the world, and congratulations for doing it so well.

  • @axay06
    @axay063 жыл бұрын

    Brackeys and Code Monkey are the best

  • @oyunlarveparodiler3221

    @oyunlarveparodiler3221

    2 жыл бұрын

    This did not age well .d

  • @frankbraker
    @frankbraker3 жыл бұрын

    Love this! I had to dig a little to make a singleton I was happy with (something I don't care about as much as I should) - but it works for now! Thanks again!

  • @pichicatoa
    @pichicatoa4 жыл бұрын

    Great video and explanation, helps me so much!!

  • @renatusdev
    @renatusdev4 жыл бұрын

    This is powerful wizardry old and wise monkey! Powerful indeed. Thank YOUUU!!

  • @jasondotjson34
    @jasondotjson344 жыл бұрын

    Very good tutorial! Thanks Code Monkey! ;)

  • @xanxusvaria8492
    @xanxusvaria84925 жыл бұрын

    Wow finally the first time in my life youtube showed me a good add because i was searching for a game programmer and boom finally found someone thanks to a add wow :)

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Glad you like what you see!

  • @jakubnowak2433
    @jakubnowak24334 жыл бұрын

    Great tutorial, it is what I was looking for. Thank you for sharing your knowledge, you are awesome. I wil recommend you to my friends, and... if I will make someday game, I will add u in credits, u helped a lot, not just in this video. Stay safe!

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    I'm glad to hear it! Best of luck!

  • @cubaindy6700
    @cubaindy67004 жыл бұрын

    Dude. Do you have any idea how good an instructor you are? I've been watching coding/unity videos for years. You are highly organized, extremely concise, and just a smart organizer of code. Level: Elite.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Thanks! I'm glad you found it useful!

  • @billmolloy2264

    @billmolloy2264

    3 жыл бұрын

    @@CodeMonkeyUnity Great tuts, many thanks!

  • @littledumpling5614

    @littledumpling5614

    3 жыл бұрын

    @@CodeMonkeyUnity Ur goated Bruh

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    @@littledumpling5614 I'm what?

  • @davidsanchezplaza

    @davidsanchezplaza

    3 жыл бұрын

    I think he means goat greatest of all times

  • @SarevansVoyage
    @SarevansVoyage5 жыл бұрын

    Thanks a lot for your information rich tutorials. I hope you keep continuing. Instead of defining a dictionary and hardcoding delay timer in a switch-case for each clip, I defined two variables in the SoundAudioClip class, one for defining the delay value in the editor, one for storing last play time. then defined a CanPlay method in SoundAudioClip class.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Great point, that would be a better way of doing things.

  • @BuckLevy

    @BuckLevy

    4 жыл бұрын

    Hey, that looks useful! Would you mind to precise a bit more how you did that? I'm new to code, and my script is going to be very long if I hardcode everything! :) Thanks

  • @jesteR_playZ_
    @jesteR_playZ_3 жыл бұрын

    i just wanna thank you man . honestly u helped me out a lot! i swear if i had any money i would totally buy all your courses! but im 14 rn so that'll take a while :)

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    I'm glad the videos helped you!

  • @LeyronMirox
    @LeyronMirox5 жыл бұрын

    The best tutor! Thanks you!

  • @mrmendee
    @mrmendee3 жыл бұрын

    This tutorial is super cool and easy to understand . Thanks for sharing your knowledge.

  • @mrmendee

    @mrmendee

    3 жыл бұрын

    I have question. How can i addsounds what if there is multiple button?

  • @whc8737
    @whc87374 жыл бұрын

    Great Tutorial!

  • @khaledguesmi6819
    @khaledguesmi68195 жыл бұрын

    I like your cool tutorials man please keep the best world

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Thanks!

  • @prolific8
    @prolific84 жыл бұрын

    Really nice tutorial and exactly what I was looking for. One question - is there really no more efficient way in Unity/C# to find the AudioClip than looping through the array? I know it's only a small array but anything with O(n) complexity makes me uncomfortable!

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    You can use a Dictionary which would be faster Or if you need to go even further you can make separate functions for each of your sounds that are used extremely often PlaySound_SwordAttack(); PlaySound_PlayerDamaged(); But at that point you're making your code worse in order to get a tiny increase in performance so only do that if you absolutely need it.

  • @dimixtyz9347
    @dimixtyz93474 жыл бұрын

    Thank you so much

  • @kristiantodt6490
    @kristiantodt64905 жыл бұрын

    I know you probably have a bunch of requests by now but I was wondering since it suits your knowledge of tycoon games if you could make a tutorial on a grid building system where you can plop down buildings. Thanks

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Yeah that's on my list, I use a pretty complicated Quadrant System in my games so I need to simplify it before making a video.

  • @FortbloxNET
    @FortbloxNET5 ай бұрын

    i love this so much!!! i will use that :D and i guess i will also update that and use scriptable objects for my soundeffects-database :)

  • @paperplane0117
    @paperplane01179 ай бұрын

    Thanks a lot man

  • @deddeniz
    @deddeniz3 жыл бұрын

    Here is a little bit cleaned up and combined with Brackeys method and some of my changes for my needs if anybody would want, it lets you - Play&Stop - Create just components, not multiple objects - Creates a Dictionary dynamically not with a switch (In my opinion switches are increases the complexity of the code I would avoid them whenever I can, It a pain in the A to add a new case each time if your game will get bigger ;P) Also, you can let me know if u think it could be even better : Sound.cs ``` using UnityEngine; using UnityEngine.Audio; [System.Serializable] public class Sound { public string name; public AudioClip clip; [Range(0f, 1f)] public float volume = 1f; [Range(.1f, 3f)] public float pitch = 1f; public bool isLoop; public bool hasCooldown; public AudioSource source; } ``` SoundManager.cs ``` using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundManager : MonoBehaviour { private static SoundManager _instance; public Sound[] sounds; private static Dictionary soundTimerDictionary; public static SoundManager instance { get { return _instance; } } private void Awake() { if (_instance != null && _instance != this) { Destroy(this.gameObject); } else { _instance = this; } soundTimerDictionary = new Dictionary(); foreach (Sound sound in sounds) { sound.source = gameObject.AddComponent(); sound.source.clip = sound.clip; sound.source.volume = sound.volume; sound.source.pitch = sound.pitch; sound.source.loop = sound.isLoop; if (sound.hasCooldown) { Debug.Log(sound.name); soundTimerDictionary[sound.name] = 0f; } } } private void Start() { // Add this part after having a theme song // Play('Theme'); } public void Play(string name) { Sound sound = Array.Find(sounds, s => s.name == name); if (sound == null) { Debug.LogError("Sound " + name + " Not Found!"); return; } if (!CanPlaySound(sound))return; sound.source.Play(); } public void Stop(string name) { Sound sound = Array.Find(sounds, s => s.name == name); if (sound == null) { Debug.LogError("Sound " + name + " Not Found!"); return; } sound.source.Stop(); } private static bool CanPlaySound(Sound sound) { if (soundTimerDictionary.ContainsKey(sound.name)) { float lastTimePlayed = soundTimerDictionary[sound.name]; if (lastTimePlayed + sound.clip.length { soundTimerDictionary[sound.name] = Time.time; return true; } return false; } return true; } } ``` and than you use like FindObjectOfType().Stop("PlayerRunning"); OR FindObjectOfType().Play("PlayerRunning");

  • @deddeniz

    @deddeniz

    3 жыл бұрын

    @Armathyx I think reason for that is to reach ppl from almost every level. Making a product code might be a bit more tricky to make tutorial about, and ppl to understand. I think the goal is to teach ppl what is possible. I am not a game dev btw just a hobbiest, so I have shared to give ppl a base if they will ever need. You should always refine code where ever u get the code from(sometimes even from docs 😂)

  • @ahmetwar1

    @ahmetwar1

    3 жыл бұрын

    dostum ben biraz acemiyim ama kodlarını kullandıktan sonra "array" kısımları bağlamda yok diyor kırmızı veriyor ne yapmak lazım

  • @deddeniz

    @deddeniz

    3 жыл бұрын

    @@ahmetwar1 merhaba, senin icin sorun olmiycaksa beni fb dan ekliyebilirsin. Ordan konusabiliriz :) Deniz Kosecioglu (mavi beyaz cizim var)

  • @ahmetwar1

    @ahmetwar1

    3 жыл бұрын

    @@deddeniz mavi beyaz bir kız çizimi vardı sadece baska bulamadım eğer o değilsen Ahmet Ural yazıp sen beni daha kolay bulabilirsin sağımda ve solumda 2 bayan var renkli bir fotoğraf

  • @deddeniz

    @deddeniz

    3 жыл бұрын

    @@ahmetwar1 muhtemelen o dur sen gonder istek ona :) Olmadi buraya email gonder ergindenizkosecioglu@gmail.com

  • @ahmedthebest
    @ahmedthebest5 жыл бұрын

    What if I attatched multiple audio sources components to game objects like component for the sword and play it from sword script when the attack happened I'm another audio source for the rute player when he moves ?

  • @danzilthard.7248
    @danzilthard.72484 жыл бұрын

    Really enjoying your guides. Is there a video that covers how you implement your Game Handler class?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    The GameHandler is just the name I use for the main script where I normally initialize things so it varies project by project. Sometimes I use it to initialize a Grid, other times spawn some enemies, etc.

  • @exarkun3263
    @exarkun32633 жыл бұрын

    If I have several different sounds that are playing in the update like the PlayerMove sound for instance, can I just create a Sound class with the soundtype (your current enum) + a bool to say if it's to be handled in the non-default case of the switch? how would you do that?

  • @TheFeesher
    @TheFeesher2 жыл бұрын

    I cannot figure this out. Using this method, is there a way I can set different clips to have different component values?? I have audio that works essentially how I want, but I wanted to modify the code a bit, and it is just not working how I want, I hope the code explains enough. The if statement I isolated is the issue. I want the loop value to be true when the Level1Music clip is created. if (CanPlaySound(sound)) { GameObject soundGameObject = new GameObject("Sound"); soundGameObject.transform.position = position; AudioSource audioSource = soundGameObject.AddComponent(); audioSource.clip = GetAudioClip(sound); Debug.Log(soundGameObject.GetComponent().clip); if (audioSource.clip.Equals(Sound.Level1Music)) { soundGameObject.GetComponent().loop = true; } audioSource.Play(); Object.Destroy(soundGameObject, audioSource.clip.length); } }

  • @lerebox
    @lerebox3 жыл бұрын

    free education.. thanks

  • @player315xbox
    @player315xbox3 жыл бұрын

    i have some questions, what if i want to play more sounds like. bulets sounds and coins, if the player grab a coin the bulet sound stops? i must add more audiosource? what if i'm using an AudioMixer channel for SFX.

  • @timothythomas5767
    @timothythomas57675 жыл бұрын

    Thanks m8

  • @aniketujgare884
    @aniketujgare8844 жыл бұрын

    I have noticed for my ui button sometime the click sound is playing twice some time like normal just one time sometime not playing at all. What is the problem? may be the scene loads fast that the sound is not playing. Can you tell how to fix this

  • @arthurleandro11
    @arthurleandro114 жыл бұрын

    I'm wrking on a game I'm making and I was having problem with the profiler. Recently I was implementing an Audio Manager as well and it was destroying my FPS, to fix it it was simple. Its terrible to have a lot of AudioClips in memory due to the fact that they'll occupy the RAM. So for Audios that it's 3D or very specific like a battle theme it' better for you developers to load them in runtime and unload them when they finish, and audio such as feedback one that are used all the time I let them in memory.At least it worked for my project. Just wanna point that out in case anyone it's having trouble with FPS really low it may be one of the problems.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Yup! Two possible performance issues when dealing with sound are spawning too many objects, which you can fix with object pooling, and high memory usage, which you can fix by limiting how many are loaded at once.

  • @goodgamershow6505

    @goodgamershow6505

    3 жыл бұрын

    i have the same problem in my project. Adding audio listener absolutely decreases FPS. Can u give me more in-depth explanation of how I can fix the problem, because i`m new to Unity?

  • @ahmedthebest
    @ahmedthebest5 жыл бұрын

    Please can you show us how to make the same scene It looked very fancy

  • @nv7287
    @nv72872 жыл бұрын

    As always amazing tutorial (I love your tutorials) - I think on this one though it didn't answer the "why build it" - why is it more efficient and better to have a sound manager? Sorry and hope it sounds like a complaint (is not really) But I always think it id good to know why an approach is needed and why to build something. - love your work a lot!!

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    The "why" is "so you can play sounds", that's really it You can also make AudioSource components on any object you want to play sound from, but it's easier to have one class capable of playing any sound anywhere

  • @shoco2
    @shoco22 жыл бұрын

    Looking at this tutorial now, I'm wondering but wouldn't calling that static method every time cause you to create a new GameObject/AudioSource every time you want to play the sound? Wouldn't it be best to just cache a reference to the previous AudioSource or something and play from that AudioSource? And if it's already playing something maybe you can then Instantiate another AudioSource, kind of like a pooling system?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    Yes ideally you would expand upon this and make use of a pooling system so you could reuse game objects.

  • @vressentials
    @vressentials2 жыл бұрын

    Great tutorial, BUT What about the load music sound on loading of scene?

  • @CertainGames1
    @CertainGames14 жыл бұрын

    nice

  • @andychan6458
    @andychan64583 жыл бұрын

    I first think code monkey can type extremely fast. I realized it is a fast forward after a while.

  • @OsvaldoG
    @OsvaldoG4 жыл бұрын

    Thanks for the video! I have a question, I want to play a sound for a button using the SoundManager and then change scene, but the scene changes very fast and doesn't wait for the sound finish. How can I add a WaitForSeconds on this SoundManager? I tried with corutines but can't add it to static class.

  • @megamasher91

    @megamasher91

    4 жыл бұрын

    Maybe add it into the scene transition script. My Scene Loading script has a coroutine that is used when I'm switching scenes. in there i have a fade to black transition. You could easily just add a 0.1 or 0.2 second coroutine in it.

  • @GeorgeWulfers_88

    @GeorgeWulfers_88

    4 жыл бұрын

    Yea, like megamasher91 said, you would want to add it to the script where ever you are calling the transition code. Play the sound first and then you would change the scenes.

  • @boxitor9355
    @boxitor93554 жыл бұрын

    how do i make if enemy is chaseing me, sound start

  • @legromorph2854
    @legromorph28543 жыл бұрын

    I get an Error when: the sound object is created and AudioSource is added, but now the PlayOneShot doesnt have a file assigned. I did everything you did by the GameAssets video. But I think the GameAssets Script does not really work for me. Do you have any tips? Thank you

  • @legromorph2854

    @legromorph2854

    3 жыл бұрын

    I have Assigned in the GameAssets a .wav file for my soundvariable but it isnt assigned (through the GameAssets script) to the audio component script as an audioclip.

  • @YYL2R2
    @YYL2R2 Жыл бұрын

    Could you make a tutorial on object pooling these sounds?

  • @Director414
    @Director4147 ай бұрын

    I've been using this for a while now. My SoundAssets is getting pretty long now. :) How would you suggest splitting it up? Make multiple SoundAssets (maybe based on different themes/subjects) ? Cheers and many thanks for this great tutorial! :)

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    7 ай бұрын

    For the enum, there's not much you can do since you can't split an enum But for the function getting the sounds, maybe you can define separate classes for each sound type and place the logic for selecting the specific sound in those classes which then call the SoundManager with all the correct individual parameters

  • @Director414

    @Director414

    7 ай бұрын

    @@CodeMonkeyUnity Thanks! In the class SoundAssets I made a few more "SoundAudioClip-arrays", but named them appropriatly, public SoundAudioClip[] soundAudioClip; public SoundAudioClip[] footsteps; public SoundAudioClip[] voices; public SoundAudioClip[] weaponry; public SoundAudioClip[] vehicles; public SoundAudioClip[] misc; Now i have some sorting at least :) Cheers and thanks for your awesome work and helpful videos!

  • @Director414

    @Director414

    7 ай бұрын

    An idea for a future video (also on the wishlist from my part) is a Sound Manager 2.0. Maybe an intermediate level tutorial featuring both pooling and some way to categorize sounds, perhaps using several dictionaries or something else in that manner. Cheers!! Appreciate everything you do here on KZread! @@CodeMonkeyUnity

  • @mateosoriortes
    @mateosoriortes Жыл бұрын

    Do you know of a way to get the cover art of an audio file from a script to display it in a Sprite?

  • @caloninsgames6481
    @caloninsgames64814 жыл бұрын

    Anybody getting compilers errors on the foreach loop. Mine is saying it can't convert audio manager game asset

  • @KazukiP
    @KazukiP2 жыл бұрын

    2:25 at this part, there is now option for a box to drop my audio source into. What am I doing wrong?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    Did you make the field public? That's all it takes

  • @Hikrauda
    @Hikrauda11 ай бұрын

    Works great! Only issue is that when the new sound object is instantiated it remains in the hierarchy, even after its played. Is there a way to destroy it easily after it plays if it's just a one-off sound?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    11 ай бұрын

    You can call Destroy(gameObject, time); it will destroy the game object after 'time' Alternatively look into object pooling

  • @Dipsoid
    @Dipsoid4 жыл бұрын

    Great tutorial, what are the benefits of putting your SoundAudioClip class into the GameAssets script rather than placing it right in the SoundManager? I tried simplifying it for myself by doing everything in the Sound Manager and am getting a CS0120 error on the GetAudioClip foreach loop which I'm assuming is because I'm trying loop through the public array in my script rather than reference the array from another script. By simplifying it, I've made it much more difficult for myself :(

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    The SoundManager is meant to be access from anywhere so it makes more sense to make it a static class. In order to store the assets in the SoundManager itself you would have to make it an instance and add the fields, essentially exactly the same thing that I did using the GameAssets. You can certainly do it but personally I find it better to keep things as separate as possible and using my standard GameAssets class makes it very easy to use.

  • @Dipsoid

    @Dipsoid

    4 жыл бұрын

    @@CodeMonkeyUnity Thanks for the speedy reply. I've got a lot to learn still.

  • @whc8737
    @whc87374 жыл бұрын

    Hello, I want to know how can we loop an Audio clip when the player is hitting a collider, if you have an idea of how can we do this using your script, I am very interested to hear your answer! Thank you for your reply!

  • @jenceslav6106

    @jenceslav6106

    4 жыл бұрын

    You can probably use: public gameObject object; // defines what object you need to collide with to play sound void OnCollisionEnter2D(Collision2D other) { if (other.gameObject == object) { //Play sound } }

  • @aishakhatoon325
    @aishakhatoon3255 жыл бұрын

    Nice tutorial but can you make a tutorial on tower defence game

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Yeah it's on my list, first I'm doing very simple games like the Snake series I just did then in the next level of complexity I'd like to do a Tower Defence.

  • @DrawMaster115
    @DrawMaster1159 ай бұрын

    Last Question, does anyone know if Button_UI has been replaced by just the Button class. Unity gives me a namespace error when I try to use Button_UI despite having the include UnityEngine.UI;

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    9 ай бұрын

    That's my own custom button class, it's not a built-in Unity thing. But yes you can use the built-in button instead

  • @user-ij9vk8bh2m
    @user-ij9vk8bh2m2 жыл бұрын

    Thanks for the video! But i steal have a question, is it possible to modify serialize class and add a volume of loaded sound?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    Yes you could modify the class to add a public float volume;

  • @user-ij9vk8bh2m

    @user-ij9vk8bh2m

    2 жыл бұрын

    @@CodeMonkeyUnity Thanks for the tip! How correct did I get it? After modyfy serealize class i added a line to the GetAudioClip method to get the volume of the current Sound and then pass it to the PlaySound method. Code of getAudioClip in 6:00 in your video

  • @maflova87

    @maflova87

    2 жыл бұрын

    @@user-ij9vk8bh2m Bit of newbie here, how did you actually added the Get Volume in the GetAudioClip method?

  • @htslai
    @htslai3 жыл бұрын

    Can you make this in visual scripting bolt Cause I don't want to code to add my car audio and

  • @jannickbreunis
    @jannickbreunis4 жыл бұрын

    I cannot initiate the GameAsset, "The object you want to initiate is null".... Confusing.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Did you place the Prefab inside the Resources folder with that exact name?

  • @aniketujgare884

    @aniketujgare884

    4 жыл бұрын

    @@CodeMonkeyUnity i also made the same mistake. Thanks Codemonkey

  • @mattshroom33

    @mattshroom33

    4 жыл бұрын

    Same mistake here. I didn't see a "resources" folder on the screen and I thought it was a variable name or something.

  • @odalmer8110

    @odalmer8110

    3 жыл бұрын

    Same mistake

  • @ineshilz

    @ineshilz

    3 жыл бұрын

    I think i have the same issue but i don't completely understand your solution... :/ I have to put my sounds in a folder called "Resources" under "Assets" ? Doesn't work for me :/ I added another folder now its Assets>Resources>SoundCollection>Sounds.wav but also doesnt work.. hmmm

  • @OddNapkin
    @OddNapkin3 жыл бұрын

    on my foreach line im getting this error error CS0030: Cannot convert type 'UnityEngine.AudioClip' to 'GameAssets.SoundAudioClip'

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    SoundAudioClip is created at 4:05

  • @DrawMaster115
    @DrawMaster1159 ай бұрын

    Does this solution allow for multiple overlapping audio clips? Is there any point in having and audio source component specific to each object that makes the noise?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    9 ай бұрын

    Yes, it will be limited to the max number of sounds Unity can play, I think it's 32, then it will sort which ones to play based on priority. Making an audiosource per object can be useful if you want to reuse objects, or simply if you have some sound that is always playing, like the players footsteps

  • @DrawMaster115

    @DrawMaster115

    9 ай бұрын

    @@CodeMonkeyUnity Thank you for answering my question, especially since the video is older.

  • @kamski3070
    @kamski30705 жыл бұрын

    Can you make a video about the infinite background(like the grass in this video)? I just want to know how to make something like this.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    The background isn't actually infinite, it's just a SpriteRenderer with the sprite set to tile with a large enough size. All it takes is to make sure your sprite is tileable.

  • @DrunkBSshow
    @DrunkBSshow4 жыл бұрын

    This is a great tutorial, but I'm getting an error. "ArgumentException: The Object you want to instantiate is null. UnityEngine.Object.CheckNullArgument(System.Object arg, System.String message)"

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Sounds like you're trying to Instantiate(); a prefab or something but the variable you're using is null. If its a [SerializedField] make sure you set the field in the Editor.

  • @ineshilz

    @ineshilz

    3 жыл бұрын

    @@CodeMonkeyUnity I get the same error, i checked multiple times if i set the sound and the Audio Clip in the ionspector :/

  • @billmolloy2264

    @billmolloy2264

    3 жыл бұрын

    @@ineshilz Game Asset prefab must be saved in a folder called Resources?

  • @michaeltorruella188

    @michaeltorruella188

    Жыл бұрын

    @@CodeMonkeyUnity No, I'm getting the same error and it's coming from your GameAssets script. The only time I try to instantiate in the whole game is with your line 23 snippet. I'm getting the same error. Is there supposed to be a prefab that we make with the GameAssets script?

  • @nimbusix7029
    @nimbusix70293 жыл бұрын

    This vid is awesome! But how do you delete instantiated sound object after it is played from SoundManager? noticed sound object just stays in scene forever.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    You can use Object.Destroy(obj, time); and use the AudioClip to see how long that sound lasts.

  • @nimbusix7029

    @nimbusix7029

    3 жыл бұрын

    @@CodeMonkeyUnity Thanks!!

  • @Hakkology
    @Hakkology Жыл бұрын

    Thank you for this great tutorial. Unfortunately, I get the error "The Object you want to instantiate is null". I put my audio files inside a file called Resources/AudioAssets and wrote the following: Instantiate(Resources.Load("AudioAssets")); What am i doing wrong ? Does this only work with "GameAssets" ? How does this code work actually ? How does it go to the assigned sound file exactly ? A bit more information would be very helpful. Thanks for this tutorial. Regards,

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    Жыл бұрын

    Did you name the asset exactly "AudioAssets"? Is it inside a Resources folder? Add a Debug.Log to find out exactly what is null unitycodemonkey.com/video.php?v=5irv30-bTJw

  • @Hakkology

    @Hakkology

    Жыл бұрын

    @@CodeMonkeyUnity Really appreciate the response. Yes to both questions, asset is named "AudioAssets" and it is inside the Resources folder. I will try to understand why it comes as null. Shame, i really loved the method you connect assets to code. Hope I can get it to work.

  • @random_precision_software
    @random_precision_software5 жыл бұрын

    Can i shoot a Ray cast out to an object instead of a straight line..the game I'm doing is a flight sim were the aim sight isn't always straight ahead cos of the camera offset..if you know what I mean

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Raycast takes a Origin point and a Direction so yes you can start from wherever and point to wherever.

  • @random_precision_software

    @random_precision_software

    5 жыл бұрын

    @@CodeMonkeyUnity but my sight isn't fixed in the middle of the screen like on FPS ,it moves with accepting the screen using world canvas(which isn't working great Amway)..how would I point out to an object..I've nether used Ray cast b4.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    You change the Origin to where you want the Raycast to start, if it's not the center of the screen then set to what you need. If you're working in 3D and testing for clicks you need to figure out the click world position so you can calculate a direction, you mouse is clicking in 2D you need to define how that translates into 3D, maybe your clicks are meant to be 100 units in front of your plane. Go play around with Raycast in an empty scene so you understand what it does and how it works.

  • @danielgarciagonzalez2391
    @danielgarciagonzalez23912 жыл бұрын

    What's this marvelous get position function I couldn't find? Is it a custom one?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    It just returns the transform.position

  • @21icetray
    @21icetray3 жыл бұрын

    I got this weird problem don't know if anyone else is having the same issue. When I fire off this code from an OnClick() event on a button, which also activates a Game Object there doesn't seem to be any sound. If it deactivates that Game Object I get sound like normal. I had this code on another button that refreshes items on the screen and sometimes it sounds fine and other times it sounds really quiet. Its a 2d game not sure why this is happening.

  • @21icetray

    @21icetray

    3 жыл бұрын

    ignore my comment it seems the sounds were too quiet because of my audio source settings if I turn up the min distance on the 3d sound setting I can hear them. Or switch volume Rolloff to Linear Rolloff I probably just missed that step in the tutorial.

  • @YolzinLive
    @YolzinLive3 жыл бұрын

    How to assign an audio mixer to the sounds we generate and play?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    The audioSource has a field for the mixer so you can modify the PlaySound(); function to also receive a target mixer

  • @Custus1599
    @Custus15993 жыл бұрын

    I followed the tutorial but when I start play I get the error "ArgumentException: The Object you want to instantiate is null."

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    Sounds like you're calling Instantiate and passing null as the parameter

  • @Nick-yb2pe
    @Nick-yb2pe4 жыл бұрын

    i keep triggering the sound in the sound manager and it just creates an empty game object with an audio source with no audio clip, have i done something wrong?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Add a Debug.Log to view the AudioClip that you're using, you're probably not getting it correctly so your setting it to null

  • @Nick-yb2pe

    @Nick-yb2pe

    4 жыл бұрын

    @@CodeMonkeyUnity thanks!

  • @noskcornarezano4173
    @noskcornarezano41734 жыл бұрын

    This is so cool! But i do have a problem, how can i refer this so i can change the volume of the fx? Even just a single control or reference to all the sound fx so i can change all the fx volumes? Please help me. Thanks

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    The class is static so you can access it from anywhere You change the volume of a sound with audioSource.volume

  • @noskcornarezano4173

    @noskcornarezano4173

    4 жыл бұрын

    ​@@CodeMonkeyUnity thank you for replying sir. but i am really a beginner. i want to refer it to my slider. but i don't know how. i tried SoundManager. (but the"oneShotAudioSource" can't get. or i tried public AudioManager GetVolume(){ return oneShotAudioSource; } but many error like not set instance..can you make a tutorial how to control volume using this script? or can you please give me an idea or line code that i could use to refer it from my volume manager? Thank you

  • @noskcornarezano4173

    @noskcornarezano4173

    4 жыл бұрын

    thank you sir. i fiz it already but i'll still view if you upload a volume manager about this script. i made it working but i know i'll learn more from you :)

  • @RubberJoelzilla
    @RubberJoelzilla4 жыл бұрын

    How do you adjust audioclip volume with this method?

  • @djalmadh1

    @djalmadh1

    4 жыл бұрын

    I did like this: public static void PlaySound(Sound sound) { GameObject soundGameObject = new GameObject("Sound"); AudioSource audioSource = soundGameObject.AddComponent(); audioSource.volume = PlayerPrefs.GetFloat("Sound"); audioSource.PlayOneShot(GetAudioClip(sound)); }

  • @mawebbzz
    @mawebbzz3 жыл бұрын

    Hello, so like I get this error "PlayOneShot was called with a null AudioClip. UnityEngine.AudioSource:PlayOneShot(AudioClip)"... And when I click on the error, it takes me to the sound manager script. What do you think is the issue?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    You are passing in a null reference kzread.info/dash/bejne/Z52m2JVpXcW6eto.html

  • @mawebbzz

    @mawebbzz

    3 жыл бұрын

    @@CodeMonkeyUnity Thank you very much it works properly now. One last question, I noticed that when the Sound gets generated in run time, I can't see the audioClips name - what would cause that?

  • @mawebbzz

    @mawebbzz

    3 жыл бұрын

    @@CodeMonkeyUnity And can this same system be used for the theme song?

  • @MrChubbyCheeksss
    @MrChubbyCheeksss3 жыл бұрын

    Hi boss @codemonkey i did the exact code that you put in there but i got an error The object you want to instantiate is null and it points to if (_i == null) _i = Instantiate(Resources.Load("GameAssets")); seems like it cannot find my files under resources even if i put it under the resources folder

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    Did you name the folder exactly "Resources" And the object inside it exactly "GameAssets"?

  • @MrChubbyCheeksss

    @MrChubbyCheeksss

    3 жыл бұрын

    @@CodeMonkeyUnity yes sir but everything is ok now aparently i have to put the gameassts script to the resource folder wahehehe thanks a bunch

  • @MrChubbyCheeksss

    @MrChubbyCheeksss

    3 жыл бұрын

    Hi sir, any idea how i can destroy the sound if the gameobject is destroyed, for example the enemy has a continous growling sound and the enemy is dead and destroyed how can we destroy the new sound gameobject?

  • @brenopejon4880

    @brenopejon4880

    3 жыл бұрын

    @@CodeMonkeyUnity Thanks!!

  • @Drodothusfaram
    @Drodothusfaram5 жыл бұрын

    you rulz!

  • @wtmftproductions
    @wtmftproductions2 жыл бұрын

    Won't this create a new GameObject in the scene every time you play a sound?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    Yes. If that causes performance issues you can just implement a pooling system

  • @mrbooscloos2431
    @mrbooscloos24313 жыл бұрын

    audioSource.PlayOneShot(PlayerController.i.Death); doesnt work and the error is: 'PlayerController' does not contain a definition for 'i'

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    You don't have any field named "i" inside PlayerController

  • @mrbooscloos2431

    @mrbooscloos2431

    3 жыл бұрын

    @@CodeMonkeyUnity So should i add one?

  • @sergio.pessegueiro
    @sergio.pessegueiro4 жыл бұрын

    How should I implement this with Unity mixer? So I can get audio settings?

  • @BuckLevy

    @BuckLevy

    4 жыл бұрын

    If anybody's looking for this, I figured out a solution: In GameAssets.cs, create a "public AudioMixerGroup SFXMixerGroup;" and add in the inspector your mixer group. Then in your SoundManager, in the PlaySound function, add the line "audioSource.outputAudioMixerGroup = GameAssets.i.SFXMixerGroup;" in your list of the audiosource options Hope that helps !

  • @aniketujgare884

    @aniketujgare884

    4 жыл бұрын

    @@BuckLevy Thanks man!! Solved my problem, after doing whatever you told + applying it to prefab.

  • @nocultist7050
    @nocultist70503 жыл бұрын

    How to make sound work in WebGL build?

  • @robosergTV
    @robosergTV3 жыл бұрын

    Hmm, why not use SO to hold sounds?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    You can, that's definitely another valid approach

  • @stlngds
    @stlngds3 жыл бұрын

    Whenever I try to play a sound, it throws a "The Object you want to instantiate is null" exception, and I can't figure out why. Any common reasons why this might happen?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    You're calling Instantiate(); with a null parameter

  • @metro9203

    @metro9203

    3 жыл бұрын

    @@CodeMonkeyUnity I tried everything, is there a solution to this?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    @@metro9203 The solution is to pass in a reference to whatever object you're trying to instantiate.

  • @francescosetragno7601

    @francescosetragno7601

    3 жыл бұрын

    @@CodeMonkeyUnity I have the same problem. I copied the code in your GameAssets file but the instantiate line throws that error.

  • @corynorris7300

    @corynorris7300

    3 жыл бұрын

    ​@@francescosetragno7601 I suspect this line throws the error: _i = Instantiate(Resources.Load("GameAssets")); To fix it I think you need a GameAssets prefab (w/ the script attached) in a Assets/Resources folder

  • @GameAudio1
    @GameAudio12 жыл бұрын

    Debug.Log(GameAssets.i.playerAttack); is null and Im not sure why.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    Did you assign the reference in the GameAssets prefab?

  • @paweldraws7800
    @paweldraws78002 жыл бұрын

    Consol shows me "NullReferenceException: Object reference not set to an instance of an object". Sound objects generate but no sound. What could be the reason?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    Use Debug.Log to find what is null unitycodemonkey.com/video.php?v=5irv30-bTJw

  • @paweldraws7800

    @paweldraws7800

    2 жыл бұрын

    @@CodeMonkeyUnity Thank you for your response. I think I checked everything. The console also says: "UnityEngine.Object.Instantiate [T] (T original) (at : 0)". Maybe they changed something in Unity?

  • @paweldraws7800

    @paweldraws7800

    2 жыл бұрын

    It was referring to "f (_i == null) _i = Instantiate (Resources.Load (" GameAssets "));"

  • @tbplays8874

    @tbplays8874

    Жыл бұрын

    ​@@paweldraws7800did you ever figure out what was wrong I have the same issue

  • @fabianobersovszky6987
    @fabianobersovszky69872 жыл бұрын

    Isn't it better to create all audio sources for all sounds at the start? So dont need to create a new object everytime i want to play a sound. So it takes RAM instead of CPU.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    Yes ideally you would want to build a simple pooling system to be able to reuse audioSources

  • @atlev
    @atlev3 жыл бұрын

    Is there a project file for this one? :)

  • @appleseedgames6934
    @appleseedgames69343 ай бұрын

    Is this very optimised though? It seems like you're creating and destroying gameobjects every single time you want to play a sound which if you want to play heaps of sounds at once it would create a big problem

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 ай бұрын

    If you're finding this is a performance bottleneck then simply implement object pooling which will solve that issue

  • @hosseinkardan7400
    @hosseinkardan7400 Жыл бұрын

    what about a sound that repeats 1000 times? how do you deal with that extra 1000 gameObject that you created? you don't mention it at all

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    Жыл бұрын

    at 17:00 I modify the code to reuse the same game object Alternatively you could also implement a pool system

  • @hosseinkardan7400

    @hosseinkardan7400

    Жыл бұрын

    @@CodeMonkeyUnity oh thanks. I thought the rest of the video goes for Button . I solve this by checking if a gameObject with the name of the sound exists then no need to create it and reuse it.

  • @anthonygibbs9245
    @anthonygibbs92453 жыл бұрын

    i have issues when I use this method with my game, sometimes the sound properly, other times it dont play at all or dont play the whole sound, anyone have any idea what I might be doing wrong??

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    Did you make the sound 2D? If its 3D is it near the camera? Is the sound object even being created? Add some Debug.Log to find out

  • @anthonygibbs9245

    @anthonygibbs9245

    3 жыл бұрын

    @@CodeMonkeyUnity the sounds are being created, I can see them but also they are not destroying after time

  • @anthonygibbs9245

    @anthonygibbs9245

    3 жыл бұрын

    @@CodeMonkeyUnity how do I know if uts a 2d sound? My game is 2d and I have no 3d elements

  • @michalski9141
    @michalski91412 жыл бұрын

    Resources.Load("smth") is null??

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    It will be null if there's nothing named exactly "smth" in the resources folder or if that object doesn't have any component of type "something"

  • @michalski9141

    @michalski9141

    2 жыл бұрын

    @@CodeMonkeyUnity okay it’s all good now, I put the script itself in resources instead of a prefab, thanks

  • @topsjohnny8131
    @topsjohnny81313 жыл бұрын

    How do i play a random sound

  • @crispybeans7330
    @crispybeans73302 жыл бұрын

    Where the hell do you put the GameAssets thing on everything or what ????????????

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    The prefab should be automatically instantiated whenever you access the instance

  • @wibudesu205
    @wibudesu2055 жыл бұрын

    Come here, cause your add

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Glad you like what you see!

  • @ignatiusreilly8280
    @ignatiusreilly82804 жыл бұрын

    What's with this new "fashion" where in instructional clips they speed everything up so it's impossible to follow? 🤔

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    I always try to stop and talk about whatever code I've written, so if you're following along just hit pause, write it yourself and continue. No one wants to see code being written in real-time, the videos would be 1hr long and no one would watch them.

  • @ignatiusreilly8280

    @ignatiusreilly8280

    4 жыл бұрын

    @@CodeMonkeyUnity Makes sense. And that's what I did, paused and rewind. Thanks for this helpful clip.

  • @mohamedessam-6228
    @mohamedessam-62285 жыл бұрын

    i look for audio manager for me at all sites and youtube and i never found what i need, but you really are the best coder I have seen , can you tell how i make a button to change sprite audio on and audio off like the image but with your code imgur.com/r5Sq91N and how to save Audio for every time i open the game by PlayerPrefs and thank you.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    When you capture your button click you can toggle the volume then check the current volume and select the correct sprite. private void OnButtonClick() { ToggleAudio(); Sprite audioSprite; if (IsAudioMuted()) { audioSprite = AudioMutedSprite; } else { audioSprite = AudioSprite; } buttonImage.sprite = audioSprite; }For saving you can just store a number for the volume PlayerPrefs.SetInt("AudioVolume", audioVolume);

  • @mohamedessam-6228

    @mohamedessam-6228

    5 жыл бұрын

    @@CodeMonkeyUnity thank you i will try it

  • @peevee5588
    @peevee55885 жыл бұрын

    reupload?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Hmm not a reupload but the system I use here is the same way I normally do things so this video has a lot in common with the video on adding Sound to the Snake game.

  • @peevee5588

    @peevee5588

    5 жыл бұрын

    @@CodeMonkeyUnity ahh. thats why it looked so similiar. Honestly i thought i had gone insane, 'cause it didnt seem quite the same. :)

  • @erenbalc8893
    @erenbalc88935 жыл бұрын

    You are writing so fast 😀

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    Heh yeah I speed up the parts where all I'm doing is writing code to make the video less boring.

  • @ahmedthebest
    @ahmedthebest5 жыл бұрын

    please can you stop speeding the video that makes me very confused

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    5 жыл бұрын

    What part confused you? If you didn't have enough time to read the code you can just pause the video.

  • @STEELTOKEN420
    @STEELTOKEN4203 жыл бұрын

    WHY can't We get any Audio without coding .. BULLSHIT

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    You can, just make a Game Object and add a AudioSource component and set whatever AudioClip you want to play.

  • @STEELTOKEN420

    @STEELTOKEN420

    3 жыл бұрын

    @@CodeMonkeyUnity I tried this ... EVERYTIME i place it , Like on the muzzle flash it ONLY makes the sound When i Select my Gun ... FRUSTRATED with Not loctaing WHERE it goes ! Can't locate the Game object it attachs to

  • @STEELTOKEN420

    @STEELTOKEN420

    3 жыл бұрын

    i got a gun pack Muzzle Effects $20 pack , and NONE of the freaking guns have any sounds !

  • @STEELTOKEN420

    @STEELTOKEN420

    3 жыл бұрын

    @@CodeMonkeyUnity I put it WHERE ?? .. i Hear my sound but NEVER when i fire !

  • @STEELTOKEN420

    @STEELTOKEN420

    3 жыл бұрын

    I tried it on the " AFTER EFFECTS to , and ONCE AGAIN , Wit hmakes the sound AS i go to the GUN , but NO when i pres the button , WHY does the AFTER effects Que the sound Before i trigger the AFTER EFFECTS ?? I totallly confused

  • @halivudestevez2
    @halivudestevez22 жыл бұрын

    wtf? class in class? you are creating a nightmare...

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    There's nothing wrong with putting a class inside another class, as long as it makes sense

  • @doriantermini
    @doriantermini3 жыл бұрын

    You're not going through the code for people who are new to coding to understand. You just tell them to write what you're typing without explaining anything. Terrible tutorial.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    If you're completely unfamiliar with C# start off with this video kzread.info/dash/bejne/e3qV27Oin6qdYaQ.html

  • @dada_mitho2430

    @dada_mitho2430

    3 жыл бұрын

    Bruh...This guy's trolling

  • @morenolovato7877
    @morenolovato78774 жыл бұрын

    I'm sorry if I sound too rude, but this code is breaking too many good-programming rules that my heart is in pain.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Can you be more specific? What do you find wrong with it?

  • @morenolovato7877

    @morenolovato7877

    4 жыл бұрын

    Some hints: a) avoid Instantiate as most you can: wuold be very bad for performance and the GC b) avoid as most you can use of GetComponent: same reasons of point a c) Avoid enumeration, move your code from data driven to code driven d) Creating Audiosource from scratch every time don't let you to setup source attributes, like spatial space, mixer chain and so on. e) Moving object cost time, avoid it at most you can f) SoundManager know everythink of any class and it is very depending I think you could easly attach a audiosource to every actor and play their specific clip

  • @skomorokh7523

    @skomorokh7523

    4 жыл бұрын

    ​@@morenolovato7877, about point c: I suppose, scriptable objects fit well here. Something like CharacterAudioCollection SO-class that contains all sounds for specific group of characters. For example, orcs and goblins may have the same behaviour but different voices. What do you think about that?

  • @Konitama

    @Konitama

    4 жыл бұрын

    ​@@morenolovato7877 a) he mentioned object pooling at the end, which would solve that problem... you can't avoid instantiating objects but you can avoid destroying them, which is where the GC would come in b) where is it using GetComponent? c) this is kind of personal preference... while sure it's good practice, there's no real problem for 90% of project doing it this way. if you're doing a professional game with a large team you're going to want to change it d) only a problem if you need that stuff e) not sure what you're talking about here... positioning the sound? f) also not sure what the problem is here As far as I'm aware, you can't play an audio source without getting the audiosource component, so that's kind of unavoidable. Saying "don't use get component" when playing audio makes no sense. I'd love to hear your solution to sound management... I'm not sure how attaching an audiosource to every single object and playing their specific clip is a better solution. That's the opposite of sound management. That's no management. How would that work if a single object needs to play several different sounds?

  • @morenolovato7877

    @morenolovato7877

    4 жыл бұрын

    Hi @@Konitama , a) In a common object pooling, objects are never destroyed. b) Min 15:45 c) Yes is a personal choice, but is an official unity best practices. d) Sure, for an amatorial game is fine, not works at all if you want some basic effect like ducking e) Yes, from the performance point of view, moving by code an object cost CPU time f) Is hard to explain in a row, take a look on this programming topic: Decoupling, injection, and Dependency About getting component: getting is different from using. A good approach is to take direct reference and use it. This because every time you use GetComponent, cost CPU time. Attaching AudioSource to object is the official Unity Component Pattern, and makes sense because it moves natively with the parent object, managing spatial parameters. You don't need to have many Audiosource for each type or instance of an audio clip, you can play different sounds in a single AudioSource. I have not one solution, every game has different needs. A common pattern is to have a Music Manager (singleton) and one or more different "Entity Sound Manager". Sorry for my bad English, is not my natural language.

  • @RegenerationOfficial
    @RegenerationOfficial3 жыл бұрын

    get a quieter keyboard, the software is at its limits to suppress you intentional bs

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    What?