Play Random Audio help

The class name of the ScriptableAudioArray is… well… ScriptableAudioArray.
Change the filename from AudioArray.cs to ScriptableAudioArray.cs as they must match or while it will compile, Unity won’t be able to properly instantiate/attach the classes.

Hey there. Ok I changed them both, as I didn’t know what one you were referring to.

I changed the Script file itself from AudioArray to ScriptableAudioArray
image

Then I actually just deleted and made a new object Create → Shared → Audio Array for the three bow sounds but also called that file ScriptableAudioArray
image

Then went back to the object that I wanted the sound on, and was now able to add the new Shared Audio Array I just made of the sounds.

Played the game and I get this error every time the bow fires

Looked at the code for line 123 in the Fighter.cs script and see this.

  • Line 123 is the line : launchAudio.PlayRandomClip();

[details="Summary"]
void Hit()
        {
            if (target == null) { return; }
            if (!GetIsInRange(target.transform)) return;

            float damage = GetComponent<BaseStats>().GetStat(Stat.Damage);
            if (currentWeapon.value.HasProjectile())
            {
                currentWeapon.value.LaunchProjectile(rightHandTransform, leftHandTransform, target, gameObject, damage);
                launchAudio.PlayRandomClip();
            }
            else
            {
                target.TakeDamage(gameObject, damage);
            }
        }
[/details]

Should “PlayRandomClip” be changed to ScriptableAudioArray? How do you know, or how does it know (Unity) to play the right bow sounds or sword sounds, or whatever sounds… if they all have the same file name?

Almost… got it working I think Brian. Thankyou for your help. :slight_smile:

Is launchAudio an AudioRandomizer?
Did you drag the AudioRandomizer into the inspector’s launchAudio field in the Fighter?

Hey there Brian:

So I tried to fix this before and I got some help from one of the other students in this class on this section in the course. He added his own audio randomizer and showed me how to add it. I actually worked on randomizing the hit AND death sounds of the enemies (and got those working), but it did NOT work on randomizing the launch sounds on the bow. So I’m trying to get the random sounds on the bow here. I completely understand how hard it is to incorporate other people code into your project, and with the added conflict of adding more than one persons code into your project… the problems keep (or chances of conflicts) keep rising.

His launchAudio IS an AudioRandomizer by the looks of it. His code is the RandomAudioPlayer.cs script in my Audio folder which I will include here. He (Todd Vance) posted this already for everyone, so I don’t see a problem posting it here again.

Summary
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;


namespace RPG.Audio
{
    [RequireComponent(typeof(AudioSource))]
    public class RandomAudioPlayer : MonoBehaviour
    {
        [Serializable]
        public class MaterialAudioOverride
        {
            public Material[] materials;
            public SoundBank[] banks;
        }

        [Serializable]
        public class SoundBank
        {
            public string name;
            public AudioClip[] clips;
        }

        public bool randomizePitch = true;
        public float pitchRandomRange = 0.2f;
        public float playDelay = 0;
        public SoundBank defaultBank = new SoundBank();
        public MaterialAudioOverride[] overrides;

        [HideInInspector]
        public bool playing;
        [HideInInspector]
        public bool canPlay;

        protected AudioSource m_Audiosource;
        protected Dictionary<Material, SoundBank[]> m_Lookup = new Dictionary<Material, SoundBank[]>();

        public AudioSource audioSource { get { return m_Audiosource; } }

        public AudioClip clip { get; private set; }

        void Awake()
        {
            m_Audiosource = GetComponent<AudioSource>();
            for (int i = 0; i < overrides.Length; i++)
            {
                foreach (var material in overrides[i].materials)
                    m_Lookup[material] = overrides[i].banks;
            }
        }

        /// <summary>
        /// Will pick a random clip to play in the assigned list. If you pass a material, it will try
        /// to find an override for that materials or play the default clip if none can ben found.
        /// </summary>
        /// <param name="overrideMaterial"></param>
        /// <returns> Return the choosen audio clip, null if none </returns>
        public AudioClip PlayRandomClip(Material overrideMaterial, int bankId = 0)
        {
#if UNITY_EDITOR
            //UnityEditor.EditorGUIUtility.PingObject(overrideMaterial);
#endif
            if (overrideMaterial == null) return null;
            return InternalPlayRandomClip(overrideMaterial, bankId);
        }

        /// <summary>
        /// Will pick a random clip to play in the assigned list.
        /// </summary>
        public void PlayRandomClip()
        {
            clip = InternalPlayRandomClip(null, bankId: 0);
        }

        AudioClip InternalPlayRandomClip(Material overrideMaterial, int bankId)
        {
            SoundBank[] banks = null;
            var bank = defaultBank;
            if (overrideMaterial != null)
                if (m_Lookup.TryGetValue(overrideMaterial, out banks))
                    if (bankId < banks.Length)
                        bank = banks[bankId];
            if (bank.clips == null || bank.clips.Length == 0)
                return null;
            var clip = bank.clips[Random.Range(0, bank.clips.Length)];

            if (clip == null)
                return null;

            m_Audiosource.pitch = randomizePitch ? Random.Range(1.0f - pitchRandomRange, 1.0f + pitchRandomRange) : 1.0f;
            m_Audiosource.clip = clip;
            m_Audiosource.PlayDelayed(playDelay);

            return clip;
        }

    }
}

And I can confirm that his code is still working, and in the inspector under the enemy it looks like this.

In answer to your second question. I did not add your AudioRandomizer to the Enemy.
So I just added it now, and dragged and dropped the Scriptable Audio Array onto it under the AudioRandomizer section

Pressed Play to test, and his random sounds still play on the enemy (getting hit, and dying), but the bow sounds still are NOT playing when we fire the bow.
Checked the console log and see this now.


I cant add the Scriptable Audio Array to the top section, so I’m at a loss for how to add what it is missing.

BUT by adding the bow random sounds to the enemy… I don’t think is what you want to be doing here right? You just want the bow, sword, spell, ect sound to play… when you can “use” that weapon (in the HIT field in the Fighter.cs script). Every sound for every weapon (Scriptable Audio Array) would then need to be on the enemy if we do it this way?

*before I sent this… I thought I would try some things.

  • I deleted the AudioRandomizer from the enemy in the inspector and looked at the other random sounds. They were added in the Audio Sources section on the Prefab.
    image

  • I went back to the projectile that was supposed to play the random sound and checked it’s audio section on the prefab, and I deleted the Random Audio Player (it doesn’t have a play on awake field, even though the Audio Source that it adds DOES, AND the play on awake is checked)

  • I then added your Audio Randomizer and Play tested… it didn’t work. (even though the Audio Source has a play on awake AND the play on awake is checked in the top section)

  • I checked the play on awake field in the Audio Randomizer section as well (twos better than one? lol), and now it works. :open_mouth:

  • I went back to the Fighter.cs script and deleted the offending line 123 which was “launchAudio.PlayRandomClip();”

  • Play tested again. ALL old sounds still work, AND the new random bow sounds work too! AND… no more errors in the console log either! :smiley:
    win win win win win… as the kids say. :wink:

Thank you again Brian for leading me along the way, and getting me to think about how this all works together. I’m getting it. Slowly… very slowly… but surely. :stuck_out_tongue:

I’m going to update the top of this post again with this new information to help others new to this, and try to maybe add the “On Awake” command to the other RandomAudioPlayer.cs script that the other user had. I don’t want to have two random audio players working at the same time. I’m also going to try and rename the “Scriptable Audio Array” to “Bow Sounds” or something more descriptive, so that it is more clear. But if that doesn’t work I guess “Scriptable Audio Array” it is. It works right now at this moment in time, and so now is the perfect time to clean things up after working on this.

Thank you again Brian. You are always willing to help, and I greatly appreciate that. Cheers and have a wonderful wonderful day. :rainbow: :star:

Your friend’s RandomAudioPlayer looks like it is geared towards dealing with footprints against varying types of surfaces…

I’m glad you have things working!

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms