public void CreateVariation(MasterAudioGroup group, MasterAudio ma, AudioClip clip)
    {
        var resourceFileName = string.Empty;
        var useLocalization = false;

        if (group.bulkVariationMode == MasterAudio.AudioLocation.ResourceFile) {
            resourceFileName = DTGUIHelper.GetResourcePath(clip, ref useLocalization);
            if (string.IsNullOrEmpty(resourceFileName)) {
                resourceFileName = clip.name;
            }
        }

        var clipName = clip.name;

        if (group.transform.FindChild(clipName) != null) {
            DTGUIHelper.ShowAlert("You already have a Variation for this Group named '" + clipName + "'. \n\nPlease rename these Variations when finished to be unique, or you may not be able to play them by name if you have a need to.");
        }

        var newVar = (GameObject)GameObject.Instantiate(ma.soundGroupVariationTemplate.gameObject, group.transform.position, Quaternion.identity);
        UndoHelper.CreateObjectForUndo(newVar, "create Variation");

        newVar.transform.name = clipName;
        newVar.transform.parent = group.transform;
        var variation = newVar.GetComponent<SoundGroupVariation>();

        if (group.bulkVariationMode == MasterAudio.AudioLocation.ResourceFile) {
            variation.audLocation = MasterAudio.AudioLocation.ResourceFile;
            variation.resourceFileName = resourceFileName;
            variation.useLocalization = useLocalization;
        } else {
            variation.VarAudio.clip = clip;
        }
    }
    public void CreateVariation(MasterAudioGroup group, MasterAudio ma, AudioClip clip)
    {
        var clipName = clip.name;

        if (group.transform.FindChild(clipName) != null) {
            GUIHelper.ShowAlert("You already have a variation for this Group named '" + clipName + "'. \n\nPlease rename these variations when finished to be unique, or you may not be able to play them by name if you have a need to.");
        }

        var newVar = (GameObject) GameObject.Instantiate(ma.soundGroupVariationTemplate.gameObject, group.transform.position, Quaternion.identity);
        newVar.audio.clip = clip;
        newVar.transform.name = clipName;
        newVar.transform.parent = group.transform;
        var variation = newVar.GetComponent<SoundGroupVariation>();
        variation.possibleName = clipName;
    }
Exemple #3
0
        // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
        public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
        {
            if (fireExitEvent && exitCustomEvent != MasterAudio.NoGroupName && !string.IsNullOrEmpty(exitCustomEvent))
            {
                MasterAudio.FireCustomEvent(exitCustomEvent, _actorTrans);
            }

            if (fireAnimTimeEvent)
            {
                fireEventStart = true;
            }

            if (fireMultiAnimTimeEvent)
            {
                _playMultiEvent1 = true;
                _playMultiEvent2 = true;
                _playMultiEvent3 = true;
                _playMultiEvent4 = true;
            }
        }
Exemple #4
0
        protected void CheckIfUnlocked()
        {
            if (State.HasBeenUnlocked)
            {
                return;
            }

            State.FirstLockDirection  = WorldMap.GetMapDirectionFromRotation(FirstLockObject);
            State.SecondLockDirection = WorldMap.GetMapDirectionFromRotation(SecondLockObject);
            State.ThirdLockDirection  = WorldMap.GetMapDirectionFromRotation(ThirdLockObject);

            if (State.FirstLockDirection == FirstLockUnlockPosition &&
                State.SecondLockDirection == SecondLockUnlockPosition &&
                State.ThirdLockDirection == ThirdLockUnlockPosition)
            {
                MasterAudio.PlaySound(MasterAudio.SoundType.Machines, worlditem.tr, UnlockSound);
                State.HasBeenUnlocked = true;
                StartCoroutine(UnlockOverTime());
            }
        }
Exemple #5
0
    public void GoBoom()
    {
        Spaces.LBE.EventParam heatLampEventParams = new Spaces.LBE.EventParam();
        heatLampEventParams.m_fParam = 1.0f;
        Spaces.LBE.SpacesEventManager.TriggerEvent(Spaces.LBE.SpacesEventType.HeatLamps, heatLampEventParams);

        if (PlayEnemyDeathParticle.instance)
        {
            PlayEnemyDeathParticle.instance.PlayDeathParticle(DeathParticleName, gameObject.transform);
            if (MasterAudio.Instance)
            {
                MasterAudio.PlaySound3DAtTransformAndForget("ExplosionGroup", transform);
            }

            if (soundEffectComponent)
            {
                soundEffectComponent.PlaySoundToServer();
            }
        }
    }
Exemple #6
0
    public IEnumerator NewRestartRotation()
    {
        if (GlobalVariables.Instance.demoEnabled)
        {
            yield break;
        }

        StopPreviousMovement();

        MasterAudio.PlaySound(SoundsManager.Instance.winSound);

        transform.DOMove(newPlayPosition, newMovementDuration * 0.5f).SetEase(cameraEaseMovement).SetId("MenuCamera");
        transform.DORotate(new Vector3(-360f, 0f, 0f), newMovementDuration, RotateMode.LocalAxisAdd).SetEase(cameraEaseMovement).SetId("MenuCamera");

        yield return(new WaitForSecondsRealtime(newMovementDuration));

        StartCoroutine(GlobalVariables.Instance.screenShakeCamera.ResetCameraRotationCoroutine());

        //transform.DORotate(newPlayRotation, 0.5f, RotateMode.Fast).SetEase(cameraEaseMovement).SetId("MenuCamera");
    }
    public IEnumerator BossHit()
    {
        _IsHit = true;
        StopCoroutine("Fire");
        Cannon_Center.SetActive(false);
        Cannon_Left.SetActive(false);
        Cannon_Right.SetActive(false);
        yield return(new WaitForSeconds(0.1f));

        animation.CrossFade("hit 1");
        health = (health - 2500);  // -10% of Boss03 health
        MasterAudio.PlaySoundAndForget("boss03_hit", 1);
        yield return(new WaitForSeconds(animation.clip.length));

        animation.CrossFade("blink");
        yield return(new WaitForSeconds(1f));

        _IsHit = false;
        StartCoroutine("Fire");
    }
        private void StopTrackers()
        {
            var grp = MasterAudio.GrabGroup(AmbientSoundGroup, false); // script execution order thing with DGSC. Need to check so warnings don't get logged.

            if (grp != null)
            {
                switch (exitMode)
                {
                case MasterAudio.AmbientSoundExitMode.StopSound:
                    MasterAudio.StopSoundGroupOfTransform(Trans, AmbientSoundGroup);
                    break;

                case MasterAudio.AmbientSoundExitMode.FadeSound:
                    MasterAudio.FadeOutSoundGroupOfTransform(Trans, AmbientSoundGroup, exitFadeTime);
                    break;
                }
            }

            RuntimeFollower = null;
        }
        // ReSharper disable once UnusedMember.Local
        void OnDisable()
        {
            if (MasterAudio.AppIsShuttingDown)
            {
                return; // do nothing
            }

            if (!IsValidSoundGroup)
            {
                return;
            }

            if (MasterAudio.SafeInstance == null)
            {
                return;
            }

            MasterAudio.RemoveDelayedAmbient(this); // make sure it doesn't start playing or have trackers if it hasn't yet (< 1 frame since enabling).
            StopTrackers();
        }
Exemple #10
0
        // ReSharper disable once UnusedMember.Local
        void OnDisable()
        {
            if (MasterAudio.AppIsShuttingDown)
            {
                return; // do nothing
            }

            if (!IsValidSoundGroup)
            {
                return;
            }

            if (MasterAudio.SafeInstance == null)
            {
                return;
            }

            MasterAudio.StopSoundGroupOfTransform(Trans, AmbientSoundGroup);
            RuntimeFollower = null;
        }
        public static void MaybeReleaseAddressable(string addressableId, bool forceRelease = false)
        {
            if (!AddressableTasksByAddressibleId.ContainsKey(addressableId))
            {
                return;
            }

            var tracker = AddressableTasksByAddressibleId[addressableId];

            if (forceRelease || tracker.UnusedSecondsLifespan == 0)
            {
                var deadHandle = tracker.AssetHandle;
                AddressableTasksByAddressibleId.Remove(addressableId);
                Addressables.Release(deadHandle);
            }
            else
            {
                MasterAudio.AddAddressableForDelayedRelease(addressableId, tracker.UnusedSecondsLifespan);
            }
        }
Exemple #12
0
    IEnumerator WaitStartScreen()
    {
        foreach (Transform t in logosParent)
        {
            t.gameObject.SetActive(false);
        }

        ShowLogo();

        bool startScreenInput = false;

        do
        {
            if (Input.GetMouseButton(0))
            {
                startScreenInput = true;
                break;
            }

            for (int i = 0; i < 2; i++)
            {
                if (GlobalVariables.Instance.rewiredPlayers[i].GetAnyButton())
                {
                    startScreenInput = true;
                    break;
                }
            }

            yield return(0);
        }while (!startScreenInput);

        VibrationManager.Instance.Vibrate(1, FeedbackType.ButtonClick);

        MasterAudio.PlaySound(SoundsManager.Instance.gameStartSound);

        yield return(StartCoroutine(cameraMovement.StartPosition()));

        StartCoroutine(OnMenuChangeEvent(mainMenuScript));

        startScreen = false;
    }
Exemple #13
0
    public void ApplySettings() // Take values from prefs and apply to game
    {
        Debug.LogError("Applying settings");

        SavedSettings SavedSettings = DataManager.Instance.PlayerData.SavedSettings;

        if (GameSceneManager.Instance != null)
        {
            ApplySensitivity();
        }

        // Sound & music
        if (!SavedSettings.EnableMusic)
        {
            MasterAudio.MuteAllPlaylists();
        }
        else
        {
            MasterAudio.UnmuteAllPlaylists();
        }
        MasterAudio.MixerMuted = !SavedSettings.EnableSounds;

        // Shadows
        QualitySettings.shadows = SavedSettings.EnableShadows ? ShadowQuality.HardOnly : ShadowQuality.Disable;

        // texture quality
        QualitySettings.masterTextureLimit = Mathf.Abs((int)SavedSettings.TextureQuality - 2);

        // lod bias
        QualitySettings.lodBias = SavedSettings.DetailsDistance == SettingLevel.HIGH ? 1 : 0.8f;

        // camera
        CameraController cam = CameraController.Instance;

        cam.GetComponent <Camera>().farClipPlane        = SavedSettings.DetailsDistance == SettingLevel.LOW ? 85 : 1000;
        cam.GetComponent <MobileColorGrading>().enabled = SavedSettings.EnableCameraFilter;
        cam.AirParticles.gameObject.SetActive(SavedSettings.EnableCameraFilter);

        // FOG
        RenderSettings.fog = SavedSettings.EnableFog;
    }
Exemple #14
0
    private void FillClips()
    {
        clipsRemaining.Clear();

        // add clips from named playlist.
        if (startPlaylistName == MasterAudio.NO_PLAYLIST_NAME)
        {
            return;
        }

        this.currentPlaylist = MasterAudio.GrabPlaylist(startPlaylistName);

        if (this.currentPlaylist == null)
        {
            return;
        }

        MusicSetting aSong = null;

        for (var i = 0; i < currentPlaylist.MusicSettings.Count; i++)
        {
            aSong = currentPlaylist.MusicSettings[i];

            if (aSong.audLocation != MasterAudio.AudioLocation.ResourceFile)
            {
                if (aSong.clip == null)
                {
                    continue;
                }
            }
            else
            { // resource file!
                if (string.IsNullOrEmpty(aSong.resourceFileName))
                {
                    continue;
                }
            }

            clipsRemaining.Add(i);
        }
    }
Exemple #15
0
        public static Transform InitAudioSourceFollower(Transform transToFollow, string followerName, string soundGroupName, string variationName, bool willFollowSource, bool willPositionOnClosestColliderPoint,
                                                        bool useTopCollider, bool useChildColliders, MasterAudio.AmbientSoundExitMode exitMode, float exitFadeTime)
        {
            if (ListenerFollower == null || FollowerHolder == null)
            {
                return(null);
            }

            var grp = MasterAudio.GrabGroup(soundGroupName);

            if (grp == null)
            {
                return(null);
            }

            if (grp.groupVariations.Count == 0)
            {
                return(null);
            }

            var triggerRadius = grp.groupVariations[0].VarAudio.maxDistance;

            var follower     = new GameObject(followerName);
            var existingDupe = FollowerHolder.GetChildTransform(followerName);

            if (existingDupe != null)
            {
                GameObject.Destroy(existingDupe.gameObject);
            }

            follower.transform.parent = FollowerHolder;
            follower.gameObject.layer = FollowerHolder.gameObject.layer;
            var followerScript = follower.gameObject.AddComponent <TransformFollower>();

            followerScript.StartFollowing(transToFollow, soundGroupName, variationName, triggerRadius, willFollowSource, willPositionOnClosestColliderPoint, useTopCollider,
                                          useChildColliders, exitMode, exitFadeTime);

            _transformFollowers.Add(followerScript);

            return(follower.transform);
        }
    public async void DOInitialCountdown(OnCountdownFinishedDelegate OnFinished)
    {
        CountdownText.gameObject.SetActive(true);
        dimmed.DOFade(0, 3.5f);

        CountdownText.color = CountdownText_NumberColor;

        CountdownText.SetText("3");

        MasterAudio.PlaySound("Countdown");

        await Task.Delay(700);

        CountdownText.SetText("2");

        MasterAudio.PlaySound("Countdown");

        await Task.Delay(700);

        CountdownText.SetText("1");

        MasterAudio.PlaySound("Countdown");

        await Task.Delay(700);

        CountdownText.color = CountdownText_GoColor;
        CountdownText.SetText("GO!");
        MasterAudio.PlaySound("CountdownFinal");


        Tween t = CountdownText.DOFade(0, 1);

        t.OnComplete(() => CountdownText.gameObject.SetActive(false));

        dimmed.gameObject.SetActive(false);

        if (OnFinished != null)
        {
            OnFinished();
        }
    }
        private void Awake()
        {
            if (!Global.IsGameInitialized)
            {
                UnityEngine.SceneManagement.SceneManager.LoadScene("Title");
                return;
            }

            MainUIManager.I.SetupStatusPanel(Global.Player.Status);
            MasterAudio.PlaySound("Field_002");

            if (Global.BattleManager.StartScene != "None")
            {
                PlayerController.I.SetPosition(Global.BattleManager.StartPosition);
            }

            FadeCanvas.I.FadeIn(() =>
            {
                FadeCanvas.I.SetRaycastTarget(false);
            });
        }
Exemple #18
0
 public bool TryToSet(float skillLevel)
 {
     if (Mode == TrapMode.Set)
     {
         Debug.Log("Mode was set, un-setting");
         Mode = TrapMode.Disabled;
         PlayAnimation(AnimationCloseClipName);
         worlditem.RefreshHud();
         return(true);
     }
     else
     {
         Debug.Log("Wasn't set, setting now");
         Mode = TrapMode.Set;
         MasterAudio.PlaySound(MasterAudio.SoundType.Machines, transform, "HuntingTrapSet");
         State.SkillOnSet = skillLevel;
         PlayAnimation(AnimationOpenClipName);
         worlditem.RefreshHud();
         return(true);
     }
 }
Exemple #19
0
    public override void FireEvent()
    {
        if (!allGroups && string.IsNullOrEmpty(soundGroupName))
        {
            Debug.LogError("You must either check 'All Groups' or enter the Sound Group Name");
            return;
        }

        if (allGroups)
        {
            var groupNames = MasterAudio.RuntimeSoundGroupNames;
            for (var i = 0; i < groupNames.Count; i++)
            {
                MasterAudio.FadeSoundGroupToVolume(groupNames[i], targetVolume, fadeTime);
            }
        }
        else
        {
            MasterAudio.FadeSoundGroupToVolume(soundGroupName, targetVolume, fadeTime);
        }
    }
    private void SetVolume()
    {
        if (!allBuses.Value && string.IsNullOrEmpty(busName.Value))
        {
            Debug.LogError("You must either check 'All Buses' or enter the Bus Name");
            return;
        }

        if (allBuses.Value)
        {
            var busNames = MasterAudio.RuntimeBusNames;
            for (var i = 0; i < busNames.Count; i++)
            {
                MasterAudio.SetBusVolumeByName(busNames[i], volume.Value);
            }
        }
        else
        {
            MasterAudio.SetBusVolumeByName(busName.Value, volume.Value);
        }
    }
    // returns a label for a group link relation comming from the given group
    private string GetGroupLinkLabel(string groupName)
    {
        var component = MasterAudio.GrabGroup(groupName, false);

        if (component == null)
        {
            return(string.Empty);
        }

        switch (component.childGroupMode)
        {
        case MasterAudioGroup.ChildGroupMode.TriggerLinkedGroupsWhenPlayed:
            return("triggers when played");

        case MasterAudioGroup.ChildGroupMode.TriggerLinkedGroupsWhenRequested:
            return("triggers when requested");

        default:
            return(string.Empty);
        }
    }
    public override void FireEvent()
    {
        if (!allBuses && string.IsNullOrEmpty(busName))
        {
            Debug.LogError("You must either check 'All Buses' or enter the Bus Name");
            return;
        }

        if (allBuses)
        {
            var busNames = MasterAudio.RuntimeBusNames;
            for (var i = 0; i < busNames.Count; i++)
            {
                MasterAudio.FadeBusToVolume(busNames[i], targetVolume, fadeTime);
            }
        }
        else
        {
            MasterAudio.FadeBusToVolume(busName, targetVolume, fadeTime);
        }
    }
    private void SetVolume()
    {
        if (!allGroups.Value && string.IsNullOrEmpty(soundGroupName.Value))
        {
            Debug.LogError("You must either check 'All Groups' or enter the Sound Group Name");
            return;
        }

        if (allGroups.Value)
        {
            var groupNames = MasterAudio.RuntimeSoundGroupNames;
            for (var i = 0; i < groupNames.Count; i++)
            {
                MasterAudio.SetGroupVolume(groupNames[i], volume.Value);
            }
        }
        else
        {
            MasterAudio.SetGroupVolume(soundGroupName.Value, volume.Value);
        }
    }
    void StartLevelFour()
    {
        StopCoroutine("InitCryoChamber");
        EndlessPersistance._CryoCount++;  // add one to the cryo counter
        switch (_UnlockLevel[3])
        {
        case false:
            LoadingUnlocked = false;
            LevelToLoad     = 0;
            MasterAudio.PlaySoundAndForget("Ethereal_Locked", 1);
            break;

        default:
            LoadingUnlocked = true;
            LevelToLoad     = 4;
            MasterAudio.PlaySoundAndForget("Ethereal_Level04", 1);
            StartCoroutine(CloseGalaxyMap());
            break;
        }
        StartCoroutine(PrepareForLoading());
    }
Exemple #25
0
    void HitSound()
    {
        switch (Morphing.IndexForm)
        {
        case 0:
            MasterAudio.PlaySound("Geant_HIT");
            break;

        case 1:
            MasterAudio.PlaySound("Sorcier_HIT");
            break;

        case 2:
            MasterAudio.PlaySound("Pb_HIT");
            break;

        case 3:
            MasterAudio.PlaySound("Ninja_HIT");
            break;
        }
    }
Exemple #26
0
    void StaminaSound()
    {
        switch (Morphing.IndexForm)
        {
        case 0:
            MasterAudio.PlaySound("Geant_HEAVYBREATH");
            break;

        case 1:
            MasterAudio.PlaySound("Sorcier_HEAVYBREATH");
            break;

        case 2:
            MasterAudio.PlaySound("Pb_HEAVYBREATH");
            break;

        case 3:
            MasterAudio.PlaySound("Ninja_ESSOUFLEE");
            break;
        }
    }
Exemple #27
0
    protected IEnumerator OnAttack()
    {
        //have to be careful here
        if (HasPrimaryTarget)
        {
            IItemOfInterest target = PrimaryTarget;
            transform.position    = PrimaryTarget.Position;
            mDamagePackage.Point  = MouthObject.position;
            mDamagePackage.Origin = MouthObject.position;
            SetVisible(true);
            GetComponent <Animation>().Play();
            if (Listener.IsInAudibleRange(Player.Local.Position, Position, Player.Local.AudibleRange, Globals.LeviathanMaxAudibleRange))
            {
                MasterAudio.PlaySound(MasterAudio.SoundType.Leviathan, transform, "Attack");
                MasterAudio.PlaySound(MasterAudio.SoundType.JumpLandWater, transform, "Land");
            }
            if (TargetSource != null)
            {
                FXManager.Get.SpawnFX(transform.position.WithY(TargetSource.WaterHeightAtPosition(transform.position)), "Leviathan Splash");
            }
            else
            {
                FXManager.Get.SpawnFX(transform.position.WithY(Ocean.Get.OceanSurfaceHeight), "Leviathan Splash");
            }
            mDamagePackage.Target      = target;
            mDamagePackage.InstantKill = true;
            DamageManager.Get.SendDamage(mDamagePackage);
            //pretty much a guarantee that this will instakill (TODO add instakill option to damage packages?)
            PrimaryTargetObject = null;

            while (GetComponent <Animation>().isPlaying)
            {
                yield return(null);
            }

            SetVisible(false);
        }
        mMode = HostileMode.CoolingOff;
        yield break;
    }
Exemple #28
0
    private IEnumerator Fire()
    {
        while (EndlessEnemySystem._GameInfo._IsBossDefeated == false)
        {
            MasterAudio.PlaySoundAndForget("boss02_punch", 1);
            animation.CrossFade("punch");
            yield return(new WaitForSeconds(0.5f));

            OuterCannon.SetActive(true);
            yield return(new WaitForSeconds(animation.clip.length));

            animation.CrossFade("idle");
            OuterCannon.SetActive(false);
            yield return(new WaitForSeconds(animation.clip.length));

            MasterAudio.PlaySoundAndForget("boss02_punch", 1);
            animation.CrossFade("punch");
            yield return(new WaitForSeconds(0.5f));

            OuterCannon.SetActive(true);
            yield return(new WaitForSeconds(animation.clip.length));

            animation.CrossFade("idle");
            OuterCannon.SetActive(false);
            yield return(new WaitForSeconds(animation.clip.length));

            MasterAudio.PlaySoundAndForget("boss02_jump", 1);
            animation.CrossFade("hpunch");
            CenterCannon.SetActive(true);
            OuterCannon.SetActive(true);
            yield return(new WaitForSeconds(animation.clip.length));

            yield return(new WaitForSeconds(animation.clip.length));

            OuterCannon.SetActive(false);
            CenterCannon.SetActive(false);
            animation.CrossFade("idle");
            yield return(new WaitForSeconds(animation.clip.length));
        }
    }
Exemple #29
0
    // TODO: Mover a coroutine por problemas de performance
    public async void TryUseDrinkAsync()
    {
        if (!GM.GameState.CanDrink())
        {
            return;
        }

        //Debug.LogError("Drinking...");

        // Update state
        GM.GameState.Drinking = true;
        GM.GameState.CurrentAvailableDrinks--;

        // Freeze
        Motor.SetMovementFreeze(true);

        MasterAudio.PlaySound3DAtTransformAndForget("Drinking", transform);

        // Call event
        GM.GameState.InvokeOnPlayerDrink(); // Call event

        GM.GameState.InvulnerabilityEndTime = Time.time + RemoteSettings.Instance.PLAYER_CHARACTER_HEAL_INVULNERABILITY_TIME;

        // Heal player
        float amount = Random.Range(RemoteSettings.Instance.PLAYER_CHARACTER_MIN_HEAL_AMOUNT, RemoteSettings.Instance.PLAYER_CHARACTER_MAX_HEAL_AMOUNT);

        GM.GameState.Player.Heal(amount);
        // Heal invaders
        foreach (InvaderController i in GM.GameState.Invaders)
        {
            amount = Random.Range(RemoteSettings.Instance.PLAYER_CHARACTER_MIN_HEAL_AMOUNT, RemoteSettings.Instance.PLAYER_CHARACTER_MAX_HEAL_AMOUNT);
            i.Heal(amount);
        }

        // Unfreeze
        await Task.Delay(RemoteSettings.Instance.PLAYER_DRINKING_FREEZE_MILLISECONDS);

        GM.GameState.Player.Motor.SetMovementFreeze(false);
        GM.GameState.Drinking = false;
    }
        public override void PushSelectedObjectToViewer()
        {
            if (mBrowserObject == null)
            {
                return;
            }
            //this means we've clicked the object
            //change the selected object
            //then change the browser object to reflect it
            //the progression is:
            //unknown->known->learned/enabled->mastered->
            if (mSelectedObject.Mastered)
            {
                mSelectedObject.Mastered       = false;
                mSelectedObject.KnowledgeState = SkillKnowledgeState.Unknown;
            }
            else
            {
                switch (mSelectedObject.KnowledgeState)
                {
                case SkillKnowledgeState.Unknown:
                default:
                    mSelectedObject.KnowledgeState = SkillKnowledgeState.Known;
                    break;

                case SkillKnowledgeState.Known:
                    mSelectedObject.KnowledgeState = SkillKnowledgeState.Enabled;
                    break;

                case SkillKnowledgeState.Enabled:
                case SkillKnowledgeState.Learned:
                    mSelectedObject.Mastered = true;
                    break;
                }
            }
            MasterAudio.PlaySound(MasterAudio.SoundType.PlayerInterface, "ButtonClickEnabled");
            GUIGenericBrowserObject bo = mBrowserObject.gameObject.GetComponent <GUIGenericBrowserObject>();

            SetBrowserObjectColors(bo, mSelectedObject);
        }
Exemple #31
0
    public override void FireEvent()
    {
        Transform transformToUse = null;

        if (useAffectedObject && AffectedObject != null)
        {
            transformToUse = AffectedObject.transform;
        }
        else if (attachee)
        {
            transformToUse = attachee.transform;
        }

        if (transformToUse)
        {
            MasterAudio.PlaySound3DAndForget(soundGroupName, transformToUse, attachToGameObject, volume, pitch, delay);
        }
        else
        {
            MasterAudio.PlaySoundAndForget(soundGroupName, volume, pitch, delay);
        }
    }
        public static AudioClip PopulateResourceSongToPlaylistController(string controllerName, string songResourceName,
                                                                         string playlistName)
        {
            var resAudioClip = Resources.Load(songResourceName) as AudioClip;

            if (resAudioClip == null)
            {
                MasterAudio.LogWarning("Resource file '" + songResourceName + "' could not be located from Playlist '" +
                                       playlistName + "'.");
                return(null);
            }

            if (!AudioUtil.AudioClipWillPreload(resAudioClip))
            {
                MasterAudio.LogWarning("Audio Clip for Resource file '" + songResourceName + "' from Playlist '" +
                                       playlistName + "' has 'Preload Audio Data' turned off, which can cause audio glitches. Resource files should always Preload Audio Data. Please turn it on.");
            }

            FinishRecordingPlaylistClip(controllerName, resAudioClip);

            return(resAudioClip);
        }
    public static void AddLedSignalLight(MasterAudio sounds, string groupName) {
        var content = new GUIContent(MasterAudioInspectorResources.LedTextures[MasterAudioInspectorResources.LedTextures.Length - 1]);

        if (Application.isPlaying) {
            var groupInfo = MasterAudio.GetGroupInfo(groupName);
            if (groupInfo != null && !groupInfo.PlayedForWarming && groupInfo.LastTimePlayed > 0f && groupInfo.LastTimePlayed <= Time.realtimeSinceStartup) {
                var timeDiff = Time.realtimeSinceStartup - groupInfo.LastTimePlayed;

                var timeSlot = (int)(timeDiff / LedFrameTime);

                if (timeSlot >= 4 && timeSlot < 5) {
                    content = new GUIContent(MasterAudioInspectorResources.LedTextures[4]);
                } else if (timeSlot >= 3 && timeSlot < 4) {
                    content = new GUIContent(MasterAudioInspectorResources.LedTextures[3]);
                } else if (timeSlot >= 2 && timeSlot < 3) {
                    content = new GUIContent(MasterAudioInspectorResources.LedTextures[2]);
                } else if (timeSlot >= 1 && timeSlot < 2) {
                    content = new GUIContent(MasterAudioInspectorResources.LedTextures[1]);
                } else if (timeSlot >= 0 && timeSlot < 1f) {
                    content = new GUIContent(MasterAudioInspectorResources.LedTextures[0]);
                }
            }
        }

        GUILayout.Label(content, EditorStyles.toolbarButton, GUILayout.Width(26));
    }
    // ReSharper disable once FunctionComplexityOverflow
    public override void OnInspectorGUI() {
        _isValid = true;

        EditorGUI.indentLevel = 0;

        _ma = MasterAudio.Instance;
        var maInScene = _ma != null;

        if (!maInScene) {
            _isValid = false;
        } else {
            _customEventNames = _ma.CustomEventNames;
        }

        _group = (MasterAudioGroup)target;
        _group = RescanChildren(_group);

        if (!_isValid) {
            return;
        }

        if (maInScene) {
            _previewer = _ma.gameObject;
            _groupNames = _ma.GroupNames;
            _groupNames.Remove(_group.name);
        }

        var isInProjectView = DTGUIHelper.IsPrefabInProjectView(_group);

        if (MasterAudioInspectorResources.LogoTexture != null) {
            DTGUIHelper.ShowHeaderTexture(MasterAudioInspectorResources.LogoTexture);
        }

        DTGUIHelper.HelpHeader("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroups.htm");

        EditorGUILayout.BeginHorizontal();

        var newVol = DTGUIHelper.DisplayVolumeField(_group.groupMasterVolume, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, 0f, true, "Group Master Volume");
        if (newVol != _group.groupMasterVolume) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Group Master Volume");
            _group.groupMasterVolume = newVol;
        }

        var button = DTGUIHelper.AddGroupButtons(_group, "Group");
        EditorGUILayout.EndHorizontal();

        switch (button) {
            case DTGUIHelper.DTFunctionButtons.Mute:
                MasterAudioInspector.MuteMixerGroup(_group, ref _isDirty, false, false);
                break;
            case DTGUIHelper.DTFunctionButtons.Solo:
                MasterAudioInspector.SoloMixerGroup(_group, ref _isDirty, false, false);
                break;
            // ReSharper disable RedundantEmptyDefaultSwitchBranch
            default:
                break;
            // ReSharper restore RedundantEmptyDefaultSwitchBranch
        }

#if UNITY_5
        if (MasterAudio.Instance.mixerSpatialBlendType == MasterAudio.AllMixerSpatialBlendType.AllowDifferentPerGroup) {
            var newSpatialType = (MasterAudio.ItemSpatialBlendType)EditorGUILayout.EnumPopup("Spatial Blend Rule", _group.spatialBlendType);
            if (newSpatialType != _group.spatialBlendType) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Spatial Blend Rule");
                _group.spatialBlendType = newSpatialType;

                if (Application.isPlaying) {
                    MasterAudio.SetGroupSpatialBlend(_group.GameObjectName);
                } else {
                    SetSpatialBlend();
                }
            }

            switch (_group.spatialBlendType) {
                case MasterAudio.ItemSpatialBlendType.ForceToCustom:
                    EditorGUI.indentLevel = 1;
                    DTGUIHelper.ShowLargeBarAlert(MasterAudioInspector.SpatialBlendSliderText);
                    var newBlend = EditorGUILayout.Slider("Spatial Blend", _group.spatialBlend, 0f, 1f);
                    if (newBlend != _group.spatialBlend) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Spatial Blend");
                        _group.spatialBlend = newBlend;

                        if (Application.isPlaying) {
                            MasterAudio.SetGroupSpatialBlend(_group.GameObjectName);
                        } else {
                            SetSpatialBlend();
                        }
                    }
                    break;
            }
        }
#endif

        EditorGUI.indentLevel = 0;
        EditorGUILayout.BeginHorizontal();
        var newTargetGone = (MasterAudioGroup.TargetDespawnedBehavior)EditorGUILayout.EnumPopup("Caller Despawned Mode", _group.targetDespawnedBehavior);
        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroups.htm#CallerDespawned");
        EditorGUILayout.EndHorizontal();
        if (newTargetGone != _group.targetDespawnedBehavior) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "Change Caller Despawned Mode");
            _group.targetDespawnedBehavior = newTargetGone;
        }

        if (_group.targetDespawnedBehavior == MasterAudioGroup.TargetDespawnedBehavior.FadeOut) {
            EditorGUI.indentLevel = 1;
            var newFade = EditorGUILayout.Slider("Fade Out Time", _group.despawnFadeTime, .1f, 20f);
            if (newFade != _group.despawnFadeTime) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "Change Called Despawned Fade Out Time");
                _group.despawnFadeTime = newFade;
            }
        }

        var groupHasResource = false;
        foreach (var t in _group.groupVariations) {
            if (t.audLocation != MasterAudio.AudioLocation.ResourceFile) {
                continue;
            }

            groupHasResource = true;
            break;
        }

        if (MasterAudio.HasAsyncResourceLoaderFeature() && groupHasResource) {
            if (maInScene && !_ma.resourceClipsAllLoadAsync) {
                var newAsync = EditorGUILayout.Toggle(new GUIContent("Load Resources Async", "Checking this means Resource files in this Sound Group will be loaded asynchronously."), _group.resourceClipsAllLoadAsync);
                if (newAsync != _group.resourceClipsAllLoadAsync) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle Load Resources Async");
                    _group.resourceClipsAllLoadAsync = newAsync;
                }
            }
        }

        EditorGUI.indentLevel = 0;
        if (MasterAudio.Instance.prioritizeOnDistance) {
            var newContinual = EditorGUILayout.Toggle("Use Clip Age Priority", _group.useClipAgePriority);
            if (newContinual != _group.useClipAgePriority) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle Use Clip Age Priority");
                _group.useClipAgePriority = newContinual;
            }
        }

        if (MasterAudio.Instance.prioritizeOnDistance) {
            var hiPri = EditorGUILayout.Toggle("Always Highest Priority", _group.alwaysHighestPriority);
            if (hiPri != _group.alwaysHighestPriority) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle Always Highest Priority");
                _group.alwaysHighestPriority = hiPri;
            }
        }

        var newLog = EditorGUILayout.Toggle("Log Sounds", _group.logSound);
        if (newLog != _group.logSound) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle Log Sounds");
            _group.logSound = newLog;
        }

        EditorGUI.indentLevel = 0;

        DTGUIHelper.VerticalSpace(1);
        DTGUIHelper.StartGroupHeader();
        EditorGUILayout.BeginHorizontal();
        var newVarSequence = (MasterAudioGroup.VariationSequence)EditorGUILayout.EnumPopup("Variation Sequence", _group.curVariationSequence);
        if (newVarSequence != _group.curVariationSequence) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Variation Sequence");
            _group.curVariationSequence = newVarSequence;
        }

        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndVertical();

        switch (_group.curVariationSequence) {
            case MasterAudioGroup.VariationSequence.TopToBottom:
                var newUseInactive = EditorGUILayout.BeginToggleGroup(" Refill Variation Pool After Inactive Time", _group.useInactivePeriodPoolRefill);
                if (newUseInactive != _group.useInactivePeriodPoolRefill) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle Inactive Refill");
                    _group.useInactivePeriodPoolRefill = newUseInactive;
                }

                EditorGUI.indentLevel = 1;
                var newInactivePeriod = EditorGUILayout.Slider(" Inactive Time (sec)", _group.inactivePeriodSeconds, .2f, 30f);
                if (newInactivePeriod != _group.inactivePeriodSeconds) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Inactive Time");
                    _group.inactivePeriodSeconds = newInactivePeriod;
                }

                EditorGUILayout.EndToggleGroup();
                break;
            case MasterAudioGroup.VariationSequence.Randomized:
                if (_group.groupVariations.Count >= MasterAudioGroup.MinNoRepeatVariations) {
                    var newRepeat = EditorGUILayout.Toggle("No-Repeat On Refill", _group.useNoRepeatRefill);
                    if (newRepeat != _group.useNoRepeatRefill) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change No-Repeat On Refill");
                        _group.useNoRepeatRefill = newRepeat;
                    }
                } else {
                    DTGUIHelper.ShowLargeBarAlert("No-Repeat is disabled unless you have at least 3 Variations.");
                }
                break;
        }

        EditorGUILayout.EndVertical();

        EditorGUI.indentLevel = 0;
        DTGUIHelper.AddSpaceForNonU5(2);
        DTGUIHelper.StartGroupHeader();
        EditorGUILayout.BeginHorizontal();
        var newVarMode = (MasterAudioGroup.VariationMode)EditorGUILayout.EnumPopup("Variation Mode", _group.curVariationMode);
        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroups.htm#VarMode");
        EditorGUILayout.EndHorizontal();
        if (newVarMode != _group.curVariationMode) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Variation Mode");
            _group.curVariationMode = newVarMode;
        }
        EditorGUILayout.EndVertical();

        EditorGUI.indentLevel = 0;

        switch (_group.curVariationMode) {
            case MasterAudioGroup.VariationMode.Normal:
                EditorGUILayout.BeginHorizontal();
                var newRetrigger = EditorGUILayout.IntSlider("Retrigger Percentage", _group.retriggerPercentage, 0, 100);
                DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroups.htm#Retrigger");
                EditorGUILayout.EndHorizontal();
                if (newRetrigger != _group.retriggerPercentage) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Retrigger Percentage");
                    _group.retriggerPercentage = newRetrigger;
                }

                var newLimitPoly = EditorGUILayout.Toggle("Limit Polyphony", _group.limitPolyphony);
                if (newLimitPoly != _group.limitPolyphony) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle Limit Polyphony");
                    _group.limitPolyphony = newLimitPoly;
                }
                if (_group.limitPolyphony) {
                    var maxVoices = 0;
                    foreach (var variation in _group.groupVariations) {
                        maxVoices += variation.weight;
                    }

                    var newVoiceLimit = EditorGUILayout.IntSlider("Polyphony Voice Limit", _group.voiceLimitCount, 1, maxVoices);
                    if (newVoiceLimit != _group.voiceLimitCount) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Polyphony Voice Limit");
                        _group.voiceLimitCount = newVoiceLimit;
                    }
                }

                var newLimitMode = (MasterAudioGroup.LimitMode)EditorGUILayout.EnumPopup("Replay Limit Mode", _group.limitMode);
                if (newLimitMode != _group.limitMode) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Replay Limit Mode");
                    _group.limitMode = newLimitMode;
                }

                switch (_group.limitMode) {
                    case MasterAudioGroup.LimitMode.FrameBased:
                        var newFrameLimit = EditorGUILayout.IntSlider("Min Frames Between", _group.limitPerXFrames, 1, 120);
                        if (newFrameLimit != _group.limitPerXFrames) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Min Frames Between");
                            _group.limitPerXFrames = newFrameLimit;
                        }
                        break;
                    case MasterAudioGroup.LimitMode.TimeBased:
                        var newMinTime = EditorGUILayout.Slider("Min Seconds Between", _group.minimumTimeBetween, 0.1f, 10f);
                        if (newMinTime != _group.minimumTimeBetween) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Min Seconds Between");
                            _group.minimumTimeBetween = newMinTime;
                        }
                        break;
                }
                break;
            case MasterAudioGroup.VariationMode.LoopedChain:
                DTGUIHelper.ShowColorWarning("In this mode, only one Variation can be played at a time.");

                var newLoopMode = (MasterAudioGroup.ChainedLoopLoopMode)EditorGUILayout.EnumPopup("Loop Mode", _group.chainLoopMode);
                if (newLoopMode != _group.chainLoopMode) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Loop Mode");
                    _group.chainLoopMode = newLoopMode;
                }

                if (_group.chainLoopMode == MasterAudioGroup.ChainedLoopLoopMode.NumberOfLoops) {
                    var newLoopCount = EditorGUILayout.IntSlider("Number of Loops", _group.chainLoopNumLoops, 1, 500);
                    if (newLoopCount != _group.chainLoopNumLoops) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Number of Loops");
                        _group.chainLoopNumLoops = newLoopCount;
                    }
                }

                var newDelayMin = EditorGUILayout.Slider("Clip Change Delay Min", _group.chainLoopDelayMin, 0f, 20f);
                if (newDelayMin != _group.chainLoopDelayMin) {
                    if (_group.chainLoopDelayMax < newDelayMin) {
                        _group.chainLoopDelayMax = newDelayMin;
                    }
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Chained Clip Delay Min");
                    _group.chainLoopDelayMin = newDelayMin;
                }

                var newDelayMax = EditorGUILayout.Slider("Clip Change Delay Max", _group.chainLoopDelayMax, 0f, 20f);
                if (newDelayMax != _group.chainLoopDelayMax) {
                    if (newDelayMax < _group.chainLoopDelayMin) {
                        newDelayMax = _group.chainLoopDelayMin;
                    }
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Chained Clip Delay Max");
                    _group.chainLoopDelayMax = newDelayMax;
                }
                break;
            case MasterAudioGroup.VariationMode.Dialog:
                DTGUIHelper.ShowColorWarning("In this mode, only one Variation can be played at a time.");

                var newUseDialog = EditorGUILayout.Toggle("Dialog Custom Fade?", _group.useDialogFadeOut);
                if (newUseDialog != _group.useDialogFadeOut) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle Dialog Custom Fade?");
                    _group.useDialogFadeOut = newUseDialog;
                }

                if (_group.useDialogFadeOut) {
                    var newFadeTime = EditorGUILayout.Slider("Custom Fade Out Time", _group.dialogFadeOutTime, 0.1f, 20f);
                    if (newFadeTime != _group.dialogFadeOutTime) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Custom Fade Out Time");
                        _group.dialogFadeOutTime = newFadeTime;
                    }
                }
                break;
        }

        EditorGUILayout.EndVertical();

        EditorGUI.indentLevel = 0;

        DTGUIHelper.AddSpaceForNonU5(2);
        DTGUIHelper.StartGroupHeader();

        var newChildMode = (MasterAudioGroup.ChildGroupMode)EditorGUILayout.EnumPopup(new GUIContent("Linked Group Mode", "Groups you set up in this section will also get played automatically when this Group plays."), _group.childGroupMode);
        if (newChildMode != _group.childGroupMode) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Linked Group Mode");
            _group.childGroupMode = newChildMode;
        }
        EditorGUILayout.EndVertical();

        if (_group.childGroupMode != MasterAudioGroup.ChildGroupMode.None) {
            if (_group.childSoundGroups.Count == 0) {
                DTGUIHelper.ShowLargeBarAlert("You have no other Groups set up to trigger.");
                EditorGUILayout.Separator();
            }

            EditorGUI.indentLevel = 0;
            for (var i = 0; i < _group.childSoundGroups.Count; i++) {
                var aGroup = _group.childSoundGroups[i];
                if (maInScene) {
                    var existingIndex = _groupNames.IndexOf(aGroup);

                    int? groupIndex = null;

                    EditorGUI.indentLevel = 0;

                    var noGroup = false;
                    var noMatch = false;

                    if (existingIndex >= 1) {
                        groupIndex = EditorGUILayout.Popup("Sound Group", existingIndex, _groupNames.ToArray());
                        if (existingIndex == 1) {
                            noGroup = true;
                        }
                    } else if (existingIndex == -1 && aGroup == MasterAudio.NoGroupName) {
                        groupIndex = EditorGUILayout.Popup("Sound Group", existingIndex, _groupNames.ToArray());
                    } else { // non-match
                        noMatch = true;
                        var newSound = EditorGUILayout.TextField("Sound Group", aGroup);
                        if (newSound != aGroup) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Sound Group");
                            _group.childSoundGroups[i] = newSound;
                        }

                        var newIndex = EditorGUILayout.Popup("All Sound Groups", -1, _groupNames.ToArray());
                        if (newIndex >= 0) {
                            groupIndex = newIndex;
                        }
                    }

                    if (noGroup) {
                        DTGUIHelper.ShowRedError("No Sound Group specified. Action will do nothing.");
                    } else if (noMatch) {
                        DTGUIHelper.ShowRedError("Sound Group found no match. Type in or choose one.");
                    }

                    if (!groupIndex.HasValue) {
                        continue;
                    }

                    if (existingIndex != groupIndex.Value) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Sound Group");
                    }
                    if (groupIndex.Value == -1) {
                        _group.childSoundGroups[i] = MasterAudio.NoGroupName;
                    } else {
                        _group.childSoundGroups[i] = _groupNames[groupIndex.Value];
                    }
                } else {
                    var newSType = EditorGUILayout.TextField("Sound Group", aGroup);
                    if (newSType == aGroup) {
                        continue;
                    }

                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Sound Group");
                    _group.childSoundGroups[i] = newSType;
                }
            }

            GUI.contentColor = DTGUIHelper.BrightButtonColor;
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button(new GUIContent("Add Trigger Group"), EditorStyles.toolbarButton, GUILayout.Width(120))) {
                _group.childSoundGroups.Add(string.Empty);
            }
            GUILayout.Space(10);
            if (GUILayout.Button(new GUIContent("Delete Trigger Group", "Delete the last Trigger Group"), EditorStyles.toolbarButton, GUILayout.Width(120))) {
                _group.childSoundGroups.RemoveAt(_group.childSoundGroups.Count - 1);
            }
            EditorGUILayout.EndHorizontal();
            GUI.contentColor = Color.white;
        }
        EditorGUILayout.EndVertical();

        EditorGUI.indentLevel = 0;

        DTGUIHelper.StartGroupHeader();

        var newUse = EditorGUILayout.BeginToggleGroup(" Group Played Event", _group.soundPlayedEventActive);
        if (newUse != _group.soundPlayedEventActive) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle expand Group Played Event");
            _group.soundPlayedEventActive = newUse;
        }
        DTGUIHelper.EndGroupHeader();

        GUI.color = Color.white;

        if (_group.soundPlayedEventActive) {
            DTGUIHelper.ShowColorWarning("When this Group plays, fire Custom Event below.");

            if (maInScene) {
                var existingIndex = _customEventNames.IndexOf(_group.soundPlayedCustomEvent);

                int? customEventIndex = null;

                EditorGUI.indentLevel = 0;

                var noEvent = false;
                var noMatch = false;

                if (existingIndex >= 1) {
                    customEventIndex = EditorGUILayout.Popup("Custom Event Name", existingIndex, _customEventNames.ToArray());
                    if (existingIndex == 1) {
                        noEvent = true;
                    }
                } else if (existingIndex == -1 && _group.soundPlayedCustomEvent == MasterAudio.NoGroupName) {
                    customEventIndex = EditorGUILayout.Popup("Custom Event Name", existingIndex, _customEventNames.ToArray());
                } else { // non-match
                    noMatch = true;
                    var newEventName = EditorGUILayout.TextField("Custom Event Name", _group.soundPlayedCustomEvent);
                    if (newEventName != _group.soundPlayedCustomEvent) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Custom Event Name");
                        _group.soundPlayedCustomEvent = newEventName;
                    }

                    var newIndex = EditorGUILayout.Popup("All Custom Events", -1, _customEventNames.ToArray());
                    if (newIndex >= 0) {
                        customEventIndex = newIndex;
                    }
                }

                if (noEvent) {
                    DTGUIHelper.ShowRedError("No Custom Event specified. This section will do nothing.");
                } else if (noMatch) {
                    DTGUIHelper.ShowRedError("Custom Event found no match. Type in or choose one.");
                }

                if (customEventIndex.HasValue) {
                    if (existingIndex != customEventIndex.Value) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Custom Event");
                    }
                    // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                    if (customEventIndex.Value == -1) {
                        _group.soundPlayedCustomEvent = MasterAudio.NoGroupName;
                    } else {
                        _group.soundPlayedCustomEvent = _customEventNames[customEventIndex.Value];
                    }
                }
            } else {
                var newCustomEvent = EditorGUILayout.TextField("Custom Event Name", _group.soundPlayedCustomEvent);
                if (newCustomEvent != _group.soundPlayedCustomEvent) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "Custom Event Name");
                    _group.soundPlayedCustomEvent = newCustomEvent;
                }
            }
        }
        EditorGUILayout.EndToggleGroup();


        int? deadChildIndex = null;

        var canCopy = false;

        if (!Application.isPlaying) {
            // bulk copy settings

            DTGUIHelper.AddSpaceForNonU5(2);
            DTGUIHelper.StartGroupHeader();


            EditorGUI.indentLevel = 1;
            EditorGUILayout.BeginHorizontal();
            var newBulk = DTGUIHelper.Foldout(_group.copySettingsExpanded, "Copy Settings");
            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroups.htm#CopySettings");
            EditorGUILayout.EndHorizontal();

            if (newBulk != _group.copySettingsExpanded) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "toggle Copy Settings");
                _group.copySettingsExpanded = newBulk;
            }

            EditorGUI.indentLevel = 0;
            EditorGUILayout.EndVertical();
            GUI.color = Color.white;

            if (_group.copySettingsExpanded) {
                if (_group.groupVariations.Count == 0) {
                    DTGUIHelper.ShowLargeBarAlert("You currently have no Variations in this Group.");
                } else if (_group.groupVariations.Count == 1) {
                    DTGUIHelper.ShowLargeBarAlert("You only have a single Variation in this Group. Nothing to copy to.");
                } else {
                    canCopy = true;

                    var varNames = new List<string>(_group.groupVariations.Count);
                    foreach (var t in _group.groupVariations) {
                        varNames.Add(t.name);
                    }

                    if (_group.selectedVariationIndex >= varNames.Count) {
                        _group.selectedVariationIndex = 0;
                    }

                    var newVar = EditorGUILayout.Popup("Source Variation", _group.selectedVariationIndex,
                        varNames.ToArray());
                    if (newVar != _group.selectedVariationIndex) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Source Variation");
                        _group.selectedVariationIndex = newVar;
                    }

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label("Target Variations");

                    GUILayout.Space(44);
                    GUI.contentColor = DTGUIHelper.BrightButtonColor;
                    if (GUILayout.Button("Check All", EditorStyles.toolbarButton, GUILayout.Width(80))) {
                        CheckAll();
                    }
                    GUILayout.Space(10);
                    if (GUILayout.Button("Uncheck All", EditorStyles.toolbarButton, GUILayout.Width(80))) {
                        UncheckAll();
                    }
                    GUILayout.FlexibleSpace();
                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.Separator();

                    DTGUIHelper.ShowColorWarning("Click buttons below to copy from Source to checked Variations.");

                    var hasSelected = GetNonMatchingVariations().Count > 0;
                    if (!hasSelected) {
                        DTGUIHelper.ShowRedError("You have no Variations checked. Please use the checkboxes.");
                        EditorGUILayout.Separator();
                    }

                    var sourceVar = _group.groupVariations[_group.selectedVariationIndex];

                    GUI.contentColor = DTGUIHelper.BrightButtonColor;
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(10);
                    const int btnWidth = 96;

                    if (GUILayout.Button("Volume", EditorStyles.toolbarButton, GUILayout.Width(btnWidth))) {
                        CopyVolumes(sourceVar);
                        _isDirty = true;
                    }
                    GUILayout.Space(10);
                    if (GUILayout.Button("Pitch", EditorStyles.toolbarButton, GUILayout.Width(btnWidth))) {
                        CopyPitches(sourceVar);
                        _isDirty = true;
                    }
                    GUILayout.Space(10);
                    if (GUILayout.Button("Loop", EditorStyles.toolbarButton, GUILayout.Width(btnWidth))) {
                        CopyLoops(sourceVar);
                        _isDirty = true;
                    }
                    EditorGUILayout.EndHorizontal();

                    DTGUIHelper.VerticalSpace(2);

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(10);
                    if (GUILayout.Button("FX Tail Time", EditorStyles.toolbarButton, GUILayout.Width(btnWidth))) {
                        CopyFxTail(sourceVar);
                        _isDirty = true;
                    }

                    GUILayout.Space(10);
                    if (GUILayout.Button("Rand. Pitch", EditorStyles.toolbarButton, GUILayout.Width(btnWidth))) {
                        CopyRandomPitch(sourceVar);
                        _isDirty = true;
                    }
                    GUILayout.Space(10);
                    if (GUILayout.Button("Rand. Volume", EditorStyles.toolbarButton, GUILayout.Width(btnWidth))) {
                        CopyRandomVolume(sourceVar);
                        _isDirty = true;
                    }
                    EditorGUILayout.EndHorizontal();
                    DTGUIHelper.VerticalSpace(2);
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(10);
                    if (GUILayout.Button("Rand. Delay", EditorStyles.toolbarButton, GUILayout.Width(btnWidth))) {
                        CopyRandomDelay(sourceVar);
                        _isDirty = true;
                    }
                    GUILayout.Space(10);
                    if (GUILayout.Button("Custom Fade", EditorStyles.toolbarButton, GUILayout.Width(btnWidth))) {
                        CopyCustomFade(sourceVar);
                        _isDirty = true;
                    }
                    EditorGUILayout.EndHorizontal();


                    GUI.contentColor = Color.white;
                }
                EditorGUILayout.Separator();
            }
            EditorGUILayout.EndVertical();

            if (!Application.isPlaying) {
                DTGUIHelper.AddSpaceForNonU5(2);
                DTGUIHelper.StartGroupHeader();

                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("Actions", EditorStyles.wordWrappedLabel, GUILayout.Width(50f));
                GUILayout.Space(30);
                GUI.contentColor = DTGUIHelper.BrightButtonColor;

                var buttonText = "Collapse All";
                var allCollapsed = true;

                foreach (var t in _group.groupVariations) {
                    if (!t.isExpanded) {
                        continue;
                    }

                    allCollapsed = false;
                    break;
                }

                if (allCollapsed) {
                    buttonText = "Expand All";
                }

                GUILayout.FlexibleSpace();
                if (GUILayout.Button(new GUIContent(buttonText), EditorStyles.toolbarButton, GUILayout.Width(80))) {
                    _isDirty = true;
                    ExpandCollapseAll(allCollapsed);
                }
                GUILayout.Space(10);

                if (GUILayout.Button(new GUIContent("Eq. Voices", "Reset Voices to one"), EditorStyles.toolbarButton,
                    GUILayout.Width(80))) {
                    _isDirty = true;
                    EqualizeWeights(_group);
                }

                GUILayout.Space(10);
                if (GUILayout.Button(new GUIContent("Eq. Volumes"), EditorStyles.toolbarButton, GUILayout.Width(80))) {
                    _isDirty = true;
                    EqualizeVariationVolumes(_group.groupVariations);
                }

                GUI.contentColor = Color.white;
                EditorGUILayout.EndHorizontal();
                DTGUIHelper.VerticalSpace(1);

                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("Localization", EditorStyles.wordWrappedLabel, GUILayout.Width(80));
                GUILayout.FlexibleSpace();
                GUI.contentColor = DTGUIHelper.BrightButtonColor;
                if (
                    GUILayout.Button(
                        new GUIContent("All Use Loc.", "Check the 'Use Localized Folder' checkbox for all Variations."),
                        EditorStyles.toolbarButton, GUILayout.Width(125))) {
                    _isDirty = true;
                    BulkUseLocalization(_group.groupVariations, true);
                }

                GUILayout.Space(10);
                if (
                    GUILayout.Button(
                        new GUIContent("None Use Loc.",
                            "Uncheck the 'Use Localized Folder' checkbox for all Variations."),
                        EditorStyles.toolbarButton, GUILayout.Width(125))) {
                    _isDirty = true;
                    BulkUseLocalization(_group.groupVariations, false);
                }

                GUI.contentColor = Color.white;
                EditorGUILayout.EndHorizontal();

                var newBulkMode = DTGUIHelper.GetRestrictedAudioLocation("Variation Create Mode",
                    _group.bulkVariationMode);
                if (newBulkMode != _group.bulkVariationMode) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _group, "change Bulk Variation Mode");
                    _group.bulkVariationMode = newBulkMode;
                }
                if (_group.bulkVariationMode == MasterAudio.AudioLocation.ResourceFile) {
                    DTGUIHelper.ShowColorWarning("Resource mode: make sure to drag from Resource folders only.");
                }

                DTGUIHelper.EndGroupHeader();
            }

            DTGUIHelper.VerticalSpace(2);

            // new variation settings
            EditorGUILayout.BeginVertical();
            var anEvent = Event.current;

            GUI.color = DTGUIHelper.BrightTextColor;

            if (isInProjectView) {
                DTGUIHelper.ShowLargeBarAlert("You are in Project View and cannot create Variations.");
            } else {
                var dragArea = GUILayoutUtility.GetRect(0f, 35f, GUILayout.ExpandWidth(true));
                GUI.Box(dragArea, "Drag Audio clips here to create Variations!");

                GUI.color = Color.white;

                switch (anEvent.type) {
                    case EventType.DragUpdated:
                    case EventType.DragPerform:
                        if (!dragArea.Contains(anEvent.mousePosition)) {
                            break;
                        }

                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                        if (anEvent.type == EventType.DragPerform) {
                            DragAndDrop.AcceptDrag();

                            foreach (var dragged in DragAndDrop.objectReferences) {
                                var aClip = dragged as AudioClip;
                                if (aClip == null) {
                                    continue;
                                }

                                CreateVariation(_group, _ma, aClip);
                            }
                        }
                        Event.current.Use();
                        break;
                }
            }
            EditorGUILayout.EndVertical();
            // end new variation settings

        } else {
            DTGUIHelper.AddSpaceForNonU5(2);
            DTGUIHelper.StartGroupHeader();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Actions", EditorStyles.wordWrappedLabel, GUILayout.Width(50f));
            GUILayout.Space(30);
            GUI.contentColor = DTGUIHelper.BrightButtonColor;

            var buttonText = "Collapse All";
            var allCollapsed = true;

            foreach (var t in _group.groupVariations) {
                if (!t.isExpanded) {
                    continue;
                }

                allCollapsed = false;
                break;
            }

            if (allCollapsed) {
                buttonText = "Expand All";
            }

            GUILayout.FlexibleSpace();
            if (GUILayout.Button(new GUIContent(buttonText), EditorStyles.toolbarButton, GUILayout.Width(80))) {
                _isDirty = true;
                ExpandCollapseAll(allCollapsed);
            }
            EditorGUILayout.EndHorizontal();
            DTGUIHelper.EndGroupHeader();
            DTGUIHelper.AddSpaceForNonU5(2);
        }

        GUI.color = Color.white;
        GUI.contentColor = Color.white;

        if (_group.groupVariations.Count == 0) {
            DTGUIHelper.ShowRedError("You currently have no Variations.");
        } else {
            for (var i = 0; i < _group.groupVariations.Count; i++) {
                var variation = _group.groupVariations[i];

                var isNotSource = _group.selectedVariationIndex != i;


                var state = variation.isExpanded;
                var text = variation.name;

                // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                if (!state) {
                    GUI.backgroundColor = DTGUIHelper.InactiveHeaderColor;
                } else {
                    GUI.backgroundColor = DTGUIHelper.ActiveHeaderColor;
                }

                GUILayout.BeginHorizontal();

#if UNITY_3_5_7
				if (!state) {
					text += " (Click to expand)";
				}
#else
                text = "<b><size=11>" + text + "</size></b>";
#endif
                if (state) {
                    text = "\u25BC " + text;
                } else {
                    text = "\u25BA " + text;
                }
                if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) {
                    state = !state;
                }

                GUI.backgroundColor = Color.white;
                if (!state) {
                    GUILayout.Space(3f);
                }

                if (state != variation.isExpanded) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, variation, "toggle Expand Variation");
                    variation.isExpanded = state;
                }

                var varIsDirty = false;

                if (canCopy) {
                    if (isNotSource) {
                        EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
                        var newChecked = EditorGUILayout.Toggle(variation.isChecked, GUILayout.Width(16), GUILayout.Height(16));
                        if (newChecked != variation.isChecked) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, variation, "toggle check Variation");
                            variation.isChecked = newChecked;
                        }
                        EditorGUILayout.EndHorizontal();
                    } else {
                        GUI.contentColor = DTGUIHelper.BrightTextColor;
                        GUILayout.Label("SOURCE", GUILayout.Width(54));
                        GUI.contentColor = Color.white;
                    }
                }

                if (GUILayout.Button(new GUIContent(MasterAudioInspectorResources.GearTexture, "Click to goto Variation"), EditorStyles.toolbarButton, GUILayout.Height(16), GUILayout.Width(40))) {
                    Selection.activeObject = variation;
                }

                if (!Application.isPlaying && !DTGUIHelper.IsPrefabInProjectView(_group)) {
                    if (GUILayout.Button(new GUIContent(MasterAudioInspectorResources.CopyTexture, "Click to clone Variation"), EditorStyles.toolbarButton, GUILayout.Height(16), GUILayout.Width(40))) {
                        CloneVariation(i);
                    }
                }

                var buttonPressed = DTGUIHelper.DTFunctionButtons.None;
                if (!isInProjectView) {
                    buttonPressed = DTGUIHelper.AddVariationButtons();
                }

                if (!Application.isPlaying && !DTGUIHelper.IsPrefabInProjectView(_group)) {
                    if (GUILayout.Button(new GUIContent(MasterAudioInspectorResources.DeleteTexture, "Click to delete this Variation"), EditorStyles.toolbarButton, GUILayout.Height(16), GUILayout.Width(40))) {
                        deadChildIndex = i;
                        _isDirty = true;
                    }
                }

                switch (buttonPressed) {
                    case DTGUIHelper.DTFunctionButtons.Play:
                        if (Application.isPlaying) {
                            MasterAudio.PlaySoundAndForget(_group.name, 1f, null, 0f, variation.name);
                        } else {
                            var calcVolume = _group.groupMasterVolume * variation.VarAudio.volume;

                            switch (variation.audLocation) {
                                case MasterAudio.AudioLocation.ResourceFile:
                                    StopPreviewer();
                                    var fileName = AudioResourceOptimizer.GetLocalizedFileName(variation.useLocalization, variation.resourceFileName);
                                    GetPreviewer().PlayOneShot(Resources.Load(fileName) as AudioClip, calcVolume);
                                    break;
                                case MasterAudio.AudioLocation.Clip:
                                    variation.VarAudio.PlayOneShot(variation.VarAudio.clip, calcVolume);
                                    break;
                                case MasterAudio.AudioLocation.FileOnInternet:
                                    if (!string.IsNullOrEmpty(variation.internetFileUrl)) {
                                        Application.OpenURL(variation.internetFileUrl);
                                    }
                                    break;
                            }

                            _isDirty = true;
                        }
                        break;
                    case DTGUIHelper.DTFunctionButtons.Stop:
                        if (Application.isPlaying) {
                            MasterAudio.StopAllOfSound(_group.name);
                        } else {
                            if (variation.audLocation == MasterAudio.AudioLocation.ResourceFile) {
                                StopPreviewer();
                            } else {
                                variation.VarAudio.Stop();
                            }
                        }
                        break;
                }

                GUILayout.Space(4);
                DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroups.htm#Variations");

                EditorGUILayout.EndHorizontal();

                if (Application.isPlaying) {
                    DTGUIHelper.BeginGroupedControls();
                    // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                    if (variation.IsPlaying && variation.VarAudio.clip != null) { // wait for Resource files to load
                        GUI.color = Color.green;

                        var percentagePlayed = (int)(variation.VarAudio.time / variation.VarAudio.clip.length * 100);

                        EditorGUILayout.LabelField(string.Format("Playing ({0}%)", percentagePlayed),
                            EditorStyles.miniButtonMid, GUILayout.Height(16));

                        variation.frames++;
                        varIsDirty = true;
                        _isDirty = true;
                    } else {
                        GUI.color = Color.red;
                        EditorGUILayout.LabelField("Not playing", EditorStyles.miniButtonMid, GUILayout.Height(16));
                    }

                    if (!variation.isExpanded) {
                        DTGUIHelper.EndGroupedControls();
                    }
                }

                GUI.backgroundColor = Color.white;
                GUI.color = Color.white;

                if (!variation.isExpanded) {
                    DTGUIHelper.VerticalSpace(4);
                    continue;
                }

                if (!Application.isPlaying) {
                    DTGUIHelper.BeginGroupedControls();
                }

                if (!Application.isPlaying) {
                    DTGUIHelper.ShowColorWarning(MasterAudio.PreviewText);
                }
                if (variation.VarAudio == null) {
                    DTGUIHelper.ShowRedError(string.Format("The Variation: '{0}' has no Audio Source.", variation.name));
                    break;
                }

                var oldLocation = variation.audLocation;
                if (!Application.isPlaying) {
                    var newLocation =
                        (MasterAudio.AudioLocation)EditorGUILayout.EnumPopup("Audio Origin", variation.audLocation);

                    if (newLocation != oldLocation) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Audio Origin");
                        variation.audLocation = newLocation;
                    }
                } else {
                    EditorGUILayout.LabelField("Audio Origin", variation.audLocation.ToString());
                }

                switch (variation.audLocation) {
                    case MasterAudio.AudioLocation.Clip:
                        var newClip = (AudioClip)EditorGUILayout.ObjectField("Audio Clip", variation.VarAudio.clip, typeof(AudioClip), false);
                        if (newClip != variation.VarAudio.clip) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation.VarAudio, "change Audio Clip");
                            variation.VarAudio.clip = newClip;
                        }
                        break;
                    case MasterAudio.AudioLocation.FileOnInternet:
                        if (oldLocation != variation.audLocation) {
                            if (variation.VarAudio.clip != null) {
                                Debug.Log("Audio clip removed to prevent unnecessary memory usage on File On Internet Variation.");
                            }
                            variation.VarAudio.clip = null;
                        }

                        if (!Application.isPlaying) {
                            var newUrl = EditorGUILayout.TextField("Internet File URL", variation.internetFileUrl);
                            if (newUrl != variation.internetFileUrl) {
                                AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Internet File URL");
                                variation.internetFileUrl = newUrl;
                            }
                        } else {
                            EditorGUILayout.LabelField("Internet File URL", variation.internetFileUrl);
                            switch (variation.internetFileLoadStatus) {
                                case MasterAudio.InternetFileLoadStatus.Loading:
                                    DTGUIHelper.ShowLargeBarAlert("Attempting to download.");
                                    break;
                                case MasterAudio.InternetFileLoadStatus.Loaded:
                                    DTGUIHelper.ShowColorWarning("Downloaded and ready to play.");
                                    break;
                                case MasterAudio.InternetFileLoadStatus.Failed:
                                    DTGUIHelper.ShowRedError("Failed Download.");
                                    break;
                            }
                        }

                        if (string.IsNullOrEmpty(variation.internetFileUrl)) {
                            DTGUIHelper.ShowLargeBarAlert("You have not specified a URL for the File On Internet. This Variation will not be available to play without one.");
                        }
                        break;
                    case MasterAudio.AudioLocation.ResourceFile:
                        if (oldLocation != variation.audLocation) {
                            if (variation.VarAudio.clip != null) {
                                Debug.Log("Audio clip removed to prevent unnecessary memory usage on Resource file Variation.");
                            }
                            variation.VarAudio.clip = null;
                        }

                        EditorGUILayout.BeginVertical();
                        var anEvent = Event.current;

                        GUI.color = DTGUIHelper.DragAreaColor;
                        var dragArea = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
                        GUI.Box(dragArea, "Drag Resource Audio clip here to use its name!");
                        GUI.color = Color.white;

                        switch (anEvent.type) {
                            case EventType.DragUpdated:
                            case EventType.DragPerform:
                                if (!dragArea.Contains(anEvent.mousePosition)) {
                                    break;
                                }

                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                                if (anEvent.type == EventType.DragPerform) {
                                    DragAndDrop.AcceptDrag();

                                    foreach (var dragged in DragAndDrop.objectReferences) {
                                        var aClip = dragged as AudioClip;
                                        if (aClip == null) {
                                            continue;
                                        }

                                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Resource Filename");
                                        var useLocalization = false;
                                        var resourceFileName = DTGUIHelper.GetResourcePath(aClip, ref useLocalization);
                                        if (string.IsNullOrEmpty(resourceFileName)) {
                                            resourceFileName = aClip.name;
                                        }

                                        variation.resourceFileName = resourceFileName;
                                        variation.useLocalization = useLocalization;
                                    }
                                }
                                Event.current.Use();
                                break;
                        }
                        EditorGUILayout.EndVertical();

                        var newFilename = EditorGUILayout.TextField("Resource Filename", variation.resourceFileName);
                        if (newFilename != variation.resourceFileName) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Resource Filename");
                            variation.resourceFileName = newFilename;
                        }

                        EditorGUI.indentLevel = 1;

                        var newLocal = EditorGUILayout.Toggle("Use Localized Folder", variation.useLocalization);
                        if (newLocal != variation.useLocalization) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, variation, "toggle Use Localized Folder");
                            variation.useLocalization = newLocal;
                        }

                        break;

                }

                EditorGUI.indentLevel = 0;

                var newVolume = DTGUIHelper.DisplayVolumeField(variation.VarAudio.volume, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, 0f, true);
                if (newVolume != variation.VarAudio.volume) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation.VarAudio, "change Volume");
                    variation.VarAudio.volume = newVolume;
                }

                var newPitch = DTGUIHelper.DisplayPitchField(variation.VarAudio.pitch);
                if (newPitch != variation.VarAudio.pitch) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation.VarAudio, "change Pitch");
                    variation.VarAudio.pitch = newPitch;
                }

                if (_group.curVariationMode == MasterAudioGroup.VariationMode.LoopedChain) {
                    DTGUIHelper.ShowLargeBarAlert("Loop Clip is always OFF for Looped Chain Groups");
                } else {
                    var newLoop = EditorGUILayout.Toggle("Loop Clip", variation.VarAudio.loop);
                    if (newLoop != variation.VarAudio.loop) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation.VarAudio, "toggle Loop Clip");
                        variation.VarAudio.loop = newLoop;
                    }
                }

                var newWeight = EditorGUILayout.IntSlider("Voices (Weight)", variation.weight, 0, 100);
                if (newWeight != variation.weight) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Voices (Weight)");
                    variation.weight = newWeight;
                }

                var newFxTailTime = EditorGUILayout.Slider("FX Tail Time", variation.fxTailTime, 0f, 10f);
                if (newFxTailTime != variation.fxTailTime) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change FX Tail Time");
                    variation.fxTailTime = newFxTailTime;
                }

                DTGUIHelper.StartGroupHeader();

                var newUseRndPitch = EditorGUILayout.BeginToggleGroup(" Use Random Pitch", variation.useRandomPitch);
                if (newUseRndPitch != variation.useRandomPitch) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "toggle Use Random Pitch");
                    variation.useRandomPitch = newUseRndPitch;
                }
                DTGUIHelper.EndGroupHeader();

                if (variation.useRandomPitch) {
                    var newMode = (SoundGroupVariation.RandomPitchMode)EditorGUILayout.EnumPopup("Pitch Compute Mode", variation.randomPitchMode);
                    if (newMode != variation.randomPitchMode) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Pitch Compute Mode");
                        variation.randomPitchMode = newMode;
                    }

                    var newPitchMin = DTGUIHelper.DisplayPitchField(variation.randomPitchMin, "Random Pitch Min");
                    if (newPitchMin != variation.randomPitchMin) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Random Pitch Min");
                        variation.randomPitchMin = newPitchMin;
                        if (variation.randomPitchMax <= variation.randomPitchMin) {
                            variation.randomPitchMax = variation.randomPitchMin;
                        }
                    }

                    var newPitchMax = DTGUIHelper.DisplayPitchField(variation.randomPitchMax, "Random Pitch Max");
                    if (newPitchMax != variation.randomPitchMax) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Random Pitch Max");
                        variation.randomPitchMax = newPitchMax;
                        if (variation.randomPitchMin > variation.randomPitchMax) {
                            variation.randomPitchMin = variation.randomPitchMax;
                        }
                    }
                }

                EditorGUILayout.EndToggleGroup();
                DTGUIHelper.AddSpaceForNonU5(2);

                DTGUIHelper.StartGroupHeader();
                var newUseRndVol = EditorGUILayout.BeginToggleGroup(" Use Random Volume", variation.useRandomVolume);
                if (newUseRndVol != variation.useRandomVolume) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "toggle Use Random Volume");
                    variation.useRandomVolume = newUseRndVol;
                }
                DTGUIHelper.EndGroupHeader();

                if (variation.useRandomVolume) {
                    var newMode = (SoundGroupVariation.RandomVolumeMode)EditorGUILayout.EnumPopup("Volume Compute Mode", variation.randomVolumeMode);
                    if (newMode != variation.randomVolumeMode) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Volume Compute Mode");
                        variation.randomVolumeMode = newMode;
                    }

                    var volMin = 0f;
                    if (variation.randomVolumeMode == SoundGroupVariation.RandomVolumeMode.AddToClipVolume) {
                        volMin = -1f;
                    }

                    var newVolMin = DTGUIHelper.DisplayVolumeField(variation.randomVolumeMin, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, volMin, true, "Random Volume Min");
                    if (newVolMin != variation.randomVolumeMin) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Random Volume Min");
                        variation.randomVolumeMin = newVolMin;
                        if (variation.randomVolumeMax <= variation.randomVolumeMin) {
                            variation.randomVolumeMax = variation.randomVolumeMin;
                        }
                    }

                    var newVolMax = DTGUIHelper.DisplayVolumeField(variation.randomVolumeMax, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, volMin, true, "Random Volume Max");
                    if (newVolMax != variation.randomVolumeMax) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Random Volume Max");
                        variation.randomVolumeMax = newVolMax;
                        if (variation.randomVolumeMin > variation.randomVolumeMax) {
                            variation.randomVolumeMin = variation.randomVolumeMax;
                        }
                    }
                }

                EditorGUILayout.EndToggleGroup();
                DTGUIHelper.AddSpaceForNonU5(2);

                DTGUIHelper.StartGroupHeader();

                var newSilence = EditorGUILayout.BeginToggleGroup(" Use Random Delay", variation.useIntroSilence);
                if (newSilence != variation.useIntroSilence) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "toggle Use Random Delay");
                    variation.useIntroSilence = newSilence;
                }
                DTGUIHelper.EndGroupHeader();

                if (variation.useIntroSilence) {
                    var newSilenceMin = EditorGUILayout.Slider("Delay Min (sec)", variation.introSilenceMin, 0f, 100f);
                    if (newSilenceMin != variation.introSilenceMin) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Delay Min (sec)");
                        variation.introSilenceMin = newSilenceMin;
                        if (variation.introSilenceMin > variation.introSilenceMax) {
                            variation.introSilenceMax = newSilenceMin;
                        }
                    }

                    var newSilenceMax = EditorGUILayout.Slider("Delay Max (sec)", variation.introSilenceMax, 0f, 100f);
                    if (newSilenceMax != variation.introSilenceMax) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Delay Max (sec)");
                        variation.introSilenceMax = newSilenceMax;
                        if (variation.introSilenceMax < variation.introSilenceMin) {
                            variation.introSilenceMin = newSilenceMax;
                        }
                    }
                }

                EditorGUILayout.EndToggleGroup();
                DTGUIHelper.AddSpaceForNonU5(2);

                DTGUIHelper.StartGroupHeader();

                var newStart = EditorGUILayout.BeginToggleGroup(" Use Random Start Position", variation.useRandomStartTime);
                if (newStart != variation.useRandomStartTime) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "toggle Use Random Start Position");
                    variation.useRandomStartTime = newStart;
                }
                DTGUIHelper.EndGroupHeader();

                if (variation.useRandomStartTime) {
                    var newMin = EditorGUILayout.Slider("Start Min (%)", variation.randomStartMinPercent, 0f, 100f);
                    if (newMin != variation.randomStartMinPercent) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "toggle Start Min (%)");
                        variation.randomStartMinPercent = newMin;
                        if (variation.randomStartMaxPercent <= variation.randomStartMinPercent) {
                            variation.randomStartMaxPercent = variation.randomStartMinPercent;
                        }
                    }

                    var newMax = EditorGUILayout.Slider("Start Max (%)", variation.randomStartMaxPercent, 0f, 100f);
                    if (newMax != variation.randomStartMaxPercent) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "toggle Start Max (%)");
                        variation.randomStartMaxPercent = newMax;
                        if (variation.randomStartMinPercent > variation.randomStartMaxPercent) {
                            variation.randomStartMinPercent = variation.randomStartMaxPercent;
                        }
                    }
                }

                EditorGUILayout.EndToggleGroup();
                DTGUIHelper.AddSpaceForNonU5(2);

                DTGUIHelper.StartGroupHeader();

                var newFades = EditorGUILayout.BeginToggleGroup(" Use Custom Fading", variation.useFades);
                if (newFades != variation.useFades) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "toggle Use Custom Fading");
                    variation.useFades = newFades;
                }
                DTGUIHelper.EndGroupHeader();

                if (variation.useFades) {
                    var newFadeIn = EditorGUILayout.Slider("Fade In Time (sec)", variation.fadeInTime, 0f, 10f);
                    if (newFadeIn != variation.fadeInTime) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Fade In Time");
                        variation.fadeInTime = newFadeIn;
                    }

                    var newFadeOut = EditorGUILayout.Slider("Fade Out time (sec)", variation.fadeOutTime, 0f, 10f);
                    if (newFadeOut != variation.fadeOutTime) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref varIsDirty, variation, "change Fade Out Time");
                        variation.fadeOutTime = newFadeOut;
                    }
                }
                EditorGUILayout.EndToggleGroup();
                DTGUIHelper.EndGroupedControls();

                DTGUIHelper.VerticalSpace(4);

                if (!varIsDirty) {
                    continue;
                }

                EditorUtility.SetDirty(variation.VarAudio);
                EditorUtility.SetDirty(variation);
            }
        }

        if (deadChildIndex.HasValue) {
            var deadVar = _group.groupVariations[deadChildIndex.Value];

            if (deadVar != null) {
                // delete variation from Hierarchy
                AudioUndoHelper.DestroyForUndo(deadVar.gameObject);
            }

            // delete group.
            _group.groupVariations.RemoveAt(deadChildIndex.Value);
        }

        if (GUI.changed || _isDirty) {
            EditorUtility.SetDirty(target);
        }

        //DrawDefaultInspector();
    }
    public static DTFunctionButtons AddPlaylistMuteButton(string itemName, MasterAudio sounds) {
        var muteContent = new GUIContent(MasterAudioInspectorResources.MuteOffTexture, "Click to mute " + itemName);

        if (sounds.playlistsMuted) {
            muteContent.image = MasterAudioInspectorResources.MuteOnTexture;
        }

        var mutePressed = GUILayout.Button(muteContent, EditorStyles.toolbarButton);

        // ReSharper disable once ConvertIfStatementToReturnStatement
        if (mutePressed != true) {
            return DTFunctionButtons.None;
        }

        return DTFunctionButtons.Mute;
    }
    public static DTFunctionButtons AddPlaylistControllerSetupButtons(PlaylistController controller, string itemName, MasterAudio sounds, bool jukeboxMode)
    {
        var deleteIcon = sounds.deleteTexture;
        var settingsIcon = sounds.settingsTexture;

        var muteContent = new GUIContent(sounds.muteOffTexture, "Click to mute " + itemName);
        if (controller.isMuted) {
            muteContent.image = sounds.muteOnTexture;
        }

        var mutePressed = GUILayout.Button(muteContent, EditorStyles.toolbarButton);

        if (!jukeboxMode) {
            // Remove Button - Process presses later
            bool goPressed = GUILayout.Button(new GUIContent(settingsIcon, "Click to edit " + itemName), EditorStyles.toolbarButton);
            bool removePressed = false;

            if (Application.isPlaying) {
                //GUILayout.Space(26);
            } else {
                removePressed = GUILayout.Button(new GUIContent(deleteIcon, "Click to delete " + itemName), EditorStyles.toolbarButton);
            }

            if (removePressed) {
                return DTFunctionButtons.Remove;
            }
            if (goPressed) {
                return DTFunctionButtons.Go;
            }
        }

        // Return the pressed button if any
        if (mutePressed) {
            return DTFunctionButtons.Mute;
        }

        return DTFunctionButtons.None;
    }
    public static DTFunctionButtons AddVariationButtons(MasterAudio sounds)
    {
        if (GUILayout.Button(new GUIContent(sounds.playTexture, "Click to preview Variation"), EditorStyles.toolbarButton, GUILayout.Width(40))) {
            return DTFunctionButtons.Play;
        }

        if (GUILayout.Button(new GUIContent(sounds.stopTrackTexture, "Click to stop audio preview"), EditorStyles.toolbarButton, GUILayout.Width(40))) {
            return DTFunctionButtons.Stop;
        }

        return DTFunctionButtons.None;
    }
    private void SortSongsAlpha(MasterAudio.Playlist aList) {
        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "Sort Playlist Songs Alpha");

        aList.MusicSettings.Sort(delegate(MusicSetting x, MusicSetting y) {
            return x.songName.CompareTo(y.songName);
        });
    }
    public static DTFunctionButtons AddMixerBusButtons(GroupBus gb, MasterAudio sounds)
    {
        var deleteIcon = sounds.deleteTexture;

        var muteContent = new GUIContent(sounds.muteOffTexture, "Click to mute bus");

        if (gb.isMuted) {
            muteContent.image = sounds.muteOnTexture;
        }

        var soloContent = new GUIContent(sounds.soloOffTexture, "Click to solo bus");

        if (gb.isSoloed) {
            soloContent.image = sounds.soloOnTexture;
        }

        bool soloPressed = GUILayout.Button(soloContent, EditorStyles.toolbarButton);
        bool mutePressed = GUILayout.Button(muteContent, EditorStyles.toolbarButton);

        bool removePressed = false;

        if (!Application.isPlaying) {
            removePressed = GUILayout.Button(new GUIContent(deleteIcon, "Click to delete bus"), EditorStyles.toolbarButton);
        } else {
            GUILayout.Space(26);
        }

        // Return the pressed button if any
        if (removePressed == true) {
            return DTFunctionButtons.Remove;
        }
        if (soloPressed == true) {
            return DTFunctionButtons.Solo;
        }
        if (mutePressed == true) {
            return DTFunctionButtons.Mute;
        }

        return DTFunctionButtons.None;
    }
    private void CreateSoundGroup(MasterAudio sounds, AudioClip aClip)
    {
        var groupName = aClip.name;

        if (sounds.soundGroupTemplate == null || sounds.soundGroupVariationTemplate == null) {
            GUIHelper.ShowAlert("Your MasterAudio prefab has been altered and cannot function properly. Please Revert it before continuing.");
            return;
        }

        if (sounds.transform.FindChild(groupName) != null) {
            GUIHelper.ShowAlert("You already have a Sound Group named '" + groupName + "'. Please rename one of them when finished.");
        }

        GameObject newGroup = (GameObject) GameObject.Instantiate(sounds.soundGroupTemplate.gameObject, sounds.transform.position, Quaternion.identity);

        var groupTrans = newGroup.transform;
        groupTrans.name = UtilStrings.CapitalizeFirstLetter(groupName);
        groupTrans.parent = sounds.transform;

        var sName = groupName;
        SoundGroupVariation variation = null;

        GameObject newVariation = (GameObject) GameObject.Instantiate(sounds.soundGroupVariationTemplate.gameObject, groupTrans.position, Quaternion.identity);

        variation = newVariation.GetComponent<SoundGroupVariation>();
        variation.possibleName = groupName;

        newVariation.audio.clip = aClip;
        newVariation.transform.name = sName;
        newVariation.transform.parent = groupTrans;
    }
    private void ExpandCollapseSongs(MasterAudio.Playlist aList, bool shouldExpand) {
        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "Expand / Collapse Playlist Songs");

        foreach (var t in aList.MusicSettings) {
            t.isExpanded = shouldExpand;
        }
    }
    private void DeleteBus(int busIndex, MasterAudio ma)
    {
        ma.groupBuses.RemoveAt(busIndex);

        MasterAudioGroup aGroup = null;

        for (var i = 0; i < this.groups.Count; i++) {
            aGroup = this.groups[i];
            if (aGroup.busIndex == -1) {
                continue;
            }
            if (aGroup.busIndex != busIndex + MasterAudio.HARD_CODED_BUS_OPTIONS) {
                continue;
            }

            aGroup.busIndex = -1;
        }

        // adjust all other groups in case the indexes moved
        for (var i = 0; i < this.groups.Count; i++) {
            aGroup = this.groups[i];
            if (aGroup.busIndex == -1) {
                continue;
            }
            if (aGroup.busIndex < MasterAudio.HARD_CODED_BUS_OPTIONS) {
                continue;
            }
            aGroup.busIndex--;
        }
    }
    private void ExpandCollapseAllPlaylists(MasterAudio sounds, bool expand)
    {
        for (var i = 0; i < sounds.musicPlaylists.Count; i++) {
            var aList = sounds.musicPlaylists[i];
            aList.isExpanded = expand;

            for (var j = 0; j < aList.MusicSettings.Count; j++) {
                var aSong = aList.MusicSettings[j];
                aSong.isExpanded = expand;
            }
        }
    }
    private void MuteBus(int busIndex, MasterAudio ma)
    {
        var bus = ma.groupBuses[busIndex];
        bus.isMuted = !bus.isMuted;
        if (bus.isSoloed) {
            bus.isSoloed = false;
        }

        MasterAudioGroup aGroup = null;

        for (var i = 0; i < this.groups.Count; i++) {
            aGroup = this.groups[i];

            if (aGroup.busIndex != MasterAudio.HARD_CODED_BUS_OPTIONS + busIndex) {
                continue;
            }

            aGroup.isMuted = !aGroup.isMuted;
            if (bus.isMuted) {
                aGroup.isSoloed = false;
            }
        }
    }
    public static JukeboxButtons AddJukeboxIcons(MasterAudio sounds)
    {
        JukeboxButtons buttonPressed = JukeboxButtons.None;

        var stopIcon = sounds.stopTrackTexture;
        var stopContent = stopIcon == null ? new GUIContent("Stop", "Stop Playlist") : new GUIContent(stopIcon, "Stop Playlist");
        var buttonWidth = stopIcon == null ? 50 : 30;
        if (GUILayout.Button(stopContent, EditorStyles.toolbarButton, GUILayout.MaxWidth(buttonWidth))) {
            buttonPressed = JukeboxButtons.Stop;
        }

        var pauseIcon = sounds.pauseTrackTexure;
        var pauseContent = pauseIcon == null ? new GUIContent("Pause", "Pause Playlist") : new GUIContent(pauseIcon, "Pause Playlist");
        buttonWidth = pauseIcon == null ? 50 : 30;
        if (GUILayout.Button(pauseContent, EditorStyles.toolbarButton, GUILayout.MaxWidth(buttonWidth))) {
            buttonPressed = JukeboxButtons.Pause;
        }

        var playIcon = sounds.playTrackTexture;
        var playContent = playIcon == null ? new GUIContent("Play", "Play Playlist") : new GUIContent(playIcon, "Play Playlist");
        buttonWidth = playIcon == null ? 50 : 30;
        if (GUILayout.Button(playContent, EditorStyles.toolbarButton, GUILayout.MaxWidth(buttonWidth))) {
            buttonPressed = JukeboxButtons.Play;
        }

        var nextTrackIcon = sounds.nextTrackTexture;
        var nextContent = nextTrackIcon == null ? new GUIContent("Next", "Next Track in Playlist") : new GUIContent(nextTrackIcon, "Next Track in Playlist");
        buttonWidth = nextTrackIcon == null ? 50 : 30;
        if (GUILayout.Button(nextContent, EditorStyles.toolbarButton, GUILayout.MaxWidth(buttonWidth))) {
            buttonPressed = JukeboxButtons.NextSong;
        }

        GUILayout.Space(10);

        var randomIcon = sounds.randomTrackTexure;
        var randomContent = randomIcon == null ? new GUIContent("Random", "Random Track in Playlist") : new GUIContent(randomIcon, "Random Track in Playlist");
        buttonWidth = randomIcon == null ? 50 : 30;
        if (GUILayout.Button(randomContent, EditorStyles.toolbarButton, GUILayout.MaxWidth(buttonWidth))) {
            buttonPressed = JukeboxButtons.RandomSong;
        }

        if (!Application.isPlaying) {
            buttonPressed = JukeboxButtons.None;
        }

        return buttonPressed;
    }
    private void AddSongToPlaylist(MasterAudio.Playlist pList, AudioClip aClip) {
        MusicSetting lastClip = null;
        if (pList.MusicSettings.Count > 0) {
            lastClip = pList.MusicSettings[pList.MusicSettings.Count - 1];
        }

        MusicSetting mus;

        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "add Song");

        if (lastClip != null && lastClip.clip == null && pList.bulkLocationMode == MasterAudio.AudioLocation.Clip) {
            mus = lastClip;
            mus.clip = aClip;
        } else if (lastClip != null && string.IsNullOrEmpty(lastClip.resourceFileName) && pList.bulkLocationMode == MasterAudio.AudioLocation.ResourceFile) {
            mus = lastClip;
            var unused = false;
            var resourceFileName = DTGUIHelper.GetResourcePath(aClip, ref unused);
            if (string.IsNullOrEmpty(resourceFileName)) {
                // ReSharper disable once RedundantAssignment
                resourceFileName = aClip.name;
            } else {
                mus.resourceFileName = resourceFileName;
            }
        } else {
            mus = new MusicSetting() {
                volume = 1f,
                pitch = 1f,
                isExpanded = true,
                audLocation = pList.bulkLocationMode
            };

            switch (pList.bulkLocationMode) {
                case MasterAudio.AudioLocation.Clip:
                    mus.clip = aClip;
                    if (aClip != null) {
                        mus.songName = aClip.name;
                    }
                    break;
                case MasterAudio.AudioLocation.ResourceFile:
                    var unused = false;
                    var resourceFileName = DTGUIHelper.GetResourcePath(aClip, ref unused);
                    if (string.IsNullOrEmpty(resourceFileName)) {
                        resourceFileName = aClip.name;
                    }

                    mus.clip = null;
                    mus.resourceFileName = resourceFileName;
                    mus.songName = aClip.name;
                    break;
            }

            pList.MusicSettings.Add(mus);
        }
    }
    public static void AddLedSignalLight(MasterAudio sounds, string groupName)
    {
        if (sounds.ledTextures.Length == 0) {
            return;
        }

        GUIContent content = new GUIContent(sounds.ledTextures[sounds.ledTextures.Length - 1]);

        if (Application.isPlaying) {
            var groupInfo = MasterAudio.GetGroupInfo(groupName);
            if (groupInfo != null && groupInfo._lastTimePlayed > 0f && groupInfo._lastTimePlayed <= Time.time) {
                var timeDiff = Time.time - groupInfo._lastTimePlayed;

                var timeSlot = (int)(timeDiff / LED_FRAME_TIME);

                if (timeSlot >= 4 && timeSlot < 5) {
                    content = new GUIContent(sounds.ledTextures[4]);
                } else if (timeSlot >= 3 && timeSlot < 4) {
                    content = new GUIContent(sounds.ledTextures[3]);
                } else if (timeSlot >= 2 && timeSlot < 3) {
                    content = new GUIContent(sounds.ledTextures[2]);
                } else if (timeSlot >= 1 && timeSlot < 2) {
                    content = new GUIContent(sounds.ledTextures[1]);
                } else if (timeSlot >= 0 && timeSlot < 1f) {
                    content = new GUIContent(sounds.ledTextures[0]);
                }
            }
        }

        GUILayout.Label(content, EditorStyles.toolbarButton, GUILayout.Width(26));
    }
    public override void OnInspectorGUI() {
        EditorGUI.indentLevel = 0;

        _sounds = (MasterAudio)target;

        if (MasterAudioInspectorResources.LogoTexture != null) {
            DTGUIHelper.ShowHeaderTexture(MasterAudioInspectorResources.LogoTexture);
        }

        ScanGroups();

        if (!_isValid) {
            return;
        }

        if (_sounds.transform.parent != null) {
            DTGUIHelper.ShowRedError("You have the Master Audio game object as a child of another game object.");
            DTGUIHelper.ShowRedError("This is not a supported scenario and some things might break. Please unparent it.");
        }

        DTGUIHelper.HelpHeader("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/MasterAudioGO.htm");

        _isDirty = false;
        _previewer = _sounds.gameObject;

        var sliderIndicatorChars = 6;
        var sliderWidth = 40;

        if (MasterAudio.UseDbScaleForVolume) {
            sliderIndicatorChars = 9;
            sliderWidth = 56;
        }

        var fakeDirty = false;
        var allowPreview = !DTGUIHelper.IsPrefabInProjectView(_sounds);

        _playlistNames = new List<string>();

        var maxPlaylistNameChars = 11;
        foreach (var t in _sounds.musicPlaylists) {
            var pList = t;

            _playlistNames.Add(pList.playlistName);
            if (pList.playlistName.Length > maxPlaylistNameChars) {
                maxPlaylistNameChars = pList.playlistName.Length;
            }
        }

        var groupNameList = GroupNameList;

        var busFilterList = new List<string> { MasterAudio.AllBusesName, MasterAudioGroup.NoBus };

        var maxChars = 9;
        var busList = new List<string> { MasterAudioGroup.NoBus, NewBusName };

        var busVoiceLimitList = new List<string> { MasterAudio.NoVoiceLimitName };

        for (var i = 1; i <= 32; i++) {
            busVoiceLimitList.Add(i.ToString());
        }

        foreach (var t in _sounds.groupBuses) {
            var bus = t;
            busList.Add(bus.busName);
            busFilterList.Add(bus.busName);

            if (bus.busName.Length > maxChars) {
                maxChars = bus.busName.Length;
            }
        }
        var busListWidth = 9 * maxChars;
        var playlistListWidth = 9 * maxPlaylistNameChars;
        var extraPlaylistLength = 0;
        if (maxPlaylistNameChars > 11) {
            extraPlaylistLength = 9 * (11 - maxPlaylistNameChars);
        }

        PlaylistController.Instances = null;
        var pcs = PlaylistController.Instances;
        var plControllerInScene = pcs.Count > 0;

        var labelWidth = 163;
        if (!MasterAudio.UseDbScaleForVolume) {
            labelWidth = 138;
        }

        if (!Application.isPlaying) {
            MasterAudio.ListenerTrans = null; // prevent caching
            _sounds.UpdateLocation();
        }

        // mixer master volume!
        EditorGUILayout.BeginHorizontal();
        var volumeBefore = _sounds._masterAudioVolume;
        GUILayout.Label(DTGUIHelper.LabelVolumeField("Master Mixer Volume"), GUILayout.Width(labelWidth));

        GUILayout.Space(5);

        var topSliderWidth = _sounds.MixerWidth;
        if (topSliderWidth == MasterAudio.MixerWidthMode.Wide) {
            topSliderWidth = MasterAudio.MixerWidthMode.Normal;
        }

        var newMasterVol = DTGUIHelper.DisplayVolumeField(_sounds._masterAudioVolume, DTGUIHelper.VolumeFieldType.GlobalVolume, topSliderWidth);
        if (newMasterVol != _sounds._masterAudioVolume) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Master Mixer Volume");
            if (Application.isPlaying) {
                MasterAudio.MasterVolumeLevel = newMasterVol;
            } else {
                _sounds._masterAudioVolume = newMasterVol;
            }
        }

        var mixerMuteButtonPressed = DTGUIHelper.AddMixerMuteButton("Mixer", _sounds);
        GUILayout.FlexibleSpace();

        if (mixerMuteButtonPressed == DTGUIHelper.DTFunctionButtons.Mute) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Mixer Mute");

            _sounds.mixerMuted = !_sounds.mixerMuted;
            if (Application.isPlaying) {
                MasterAudio.MixerMuted = _sounds.mixerMuted;
            } else {
                foreach (var aGroup in groups) {
                    aGroup.isMuted = _sounds.mixerMuted;
                    if (aGroup.isMuted) {
                        aGroup.isSoloed = false;
                    }
                }
            }
        }

        EditorGUILayout.EndHorizontal();

        if (volumeBefore != _sounds._masterAudioVolume) {
            // fix it for realtime adjustments!
            MasterAudio.MasterVolumeLevel = _sounds._masterAudioVolume;
        }

        // playlist master volume!
        if (plControllerInScene) {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label(DTGUIHelper.LabelVolumeField("Master Playlist Volume"), GUILayout.Width(labelWidth));
            GUILayout.Space(5);
            var newPlaylistVol = DTGUIHelper.DisplayVolumeField(_sounds._masterPlaylistVolume, DTGUIHelper.VolumeFieldType.GlobalVolume, topSliderWidth);
            if (newPlaylistVol != _sounds._masterPlaylistVolume) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Master Playlist Volume");
                if (Application.isPlaying) {
                    MasterAudio.PlaylistMasterVolume = newPlaylistVol;
                } else {
                    _sounds._masterPlaylistVolume = newPlaylistVol;
                }
            }

            var playlistMuteButtonPressed = DTGUIHelper.AddPlaylistMuteButton("All Playlists", _sounds);
            if (playlistMuteButtonPressed == DTGUIHelper.DTFunctionButtons.Mute) {
                if (Application.isPlaying) {
                    MasterAudio.PlaylistsMuted = !MasterAudio.PlaylistsMuted;
                } else {
                    _sounds.playlistsMuted = !_sounds.playlistsMuted;

                    foreach (var t in pcs) {
                        if (_sounds.playlistsMuted) {
                            t.MutePlaylist();
                        } else {
                            t.UnmutePlaylist();
                        }

                        EditorUtility.SetDirty(t);
                    }
                }
            }

            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Master Crossfade Time", GUILayout.Width(labelWidth));

            GUILayout.Space(5);
            var width = topSliderWidth == MasterAudio.MixerWidthMode.Narrow ? 61 : 198;
            var newCrossTime = GUILayout.HorizontalSlider(_sounds.crossFadeTime, 0f, MasterAudio.MaxCrossFadeTimeSeconds, GUILayout.Width(width));
            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (newCrossTime != _sounds.crossFadeTime) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Master Crossfade Time");
                _sounds.crossFadeTime = newCrossTime;
            }

            var newCross = EditorGUILayout.FloatField(_sounds.crossFadeTime, GUILayout.Width(50));
            if (newCross != _sounds.crossFadeTime) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Master Crossfade Time");
                if (newCross < 0) {
                    newCross = 0;
                } else if (newCross > 10) {
                    newCross = 10;
                }
                _sounds.crossFadeTime = newCross;
            }

            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            // jukebox controls
            if (Application.isPlaying) {
                DisplayJukebox();
            }
        } else {
            DTGUIHelper.VerticalSpace(2);
        }

        // Localization section Start
        EditorGUI.indentLevel = 0;

        var state = _sounds.showLocalization;
        var text = "Languages";

        // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
        if (!state) {
            GUI.backgroundColor = DTGUIHelper.InactiveHeaderColor;
        } else {
            GUI.backgroundColor = DTGUIHelper.ActiveHeaderColor;
        }

        GUILayout.BeginHorizontal();

#if UNITY_3_5_7
        if (!state) {
            text += " (Click to expand)";
        }
#else
        text = "<b><size=11>" + text + "</size></b>";
#endif
        if (state) {
            text = "\u25BC " + text;
        } else {
            text = "\u25BA " + text;
        }
        if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) {
            state = !state;
        }

        GUILayout.Space(2f);

        if (state != _sounds.showLocalization) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Languages");
            _sounds.showLocalization = state;
        }

        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/Localization.htm");

        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        if (_sounds.showLocalization) {
            DTGUIHelper.BeginGroupedControls();
            if (Application.isPlaying) {
                DTGUIHelper.ShowColorWarning("Language settings cannot be changed during runtime");
            } else {
                int? langToRemove = null;
                int? langToAdd = null;

                for (var i = 0; i < _sounds.supportedLanguages.Count; i++) {
                    var aLang = _sounds.supportedLanguages[i];

                    DTGUIHelper.StartGroupHeader();
                    EditorGUILayout.BeginHorizontal();

                    EditorGUILayout.LabelField("Supported Lang. " + (i + 1), GUILayout.Width(120));
                    var newLang = (SystemLanguage)EditorGUILayout.EnumPopup("", aLang, GUILayout.Width(130));
                    if (newLang != aLang) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Supported Language");
                        _sounds.supportedLanguages[i] = newLang;
                    }
                    GUILayout.FlexibleSpace();

                    var buttonPressed = DTGUIHelper.AddFoldOutListItemButtonItems(i, _sounds.supportedLanguages.Count, "Supported Language", true);

                    switch (buttonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            langToRemove = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Add:
                            langToAdd = i;
                            break;
                    }

                    EditorGUILayout.EndHorizontal();
                    DTGUIHelper.EndGroupHeader();
                    DTGUIHelper.AddSpaceForNonU5(2);
                }

                if (langToAdd.HasValue) {
                    _sounds.supportedLanguages.Insert(langToAdd.Value + 1, SystemLanguage.Unknown);
                } else if (langToRemove.HasValue) {
                    if (_sounds.supportedLanguages.Count <= 1) {
                        DTGUIHelper.ShowAlert("You cannot delete the last Supported Language, although you do not have to use Localization.");
                    } else {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "Delete Supported Language");
                        _sounds.supportedLanguages.RemoveAt(langToRemove.Value);
                    }
                }

                if (!_sounds.supportedLanguages.Contains(_sounds.defaultLanguage)) {
                    DTGUIHelper.ShowLargeBarAlert("Please add your default language under Supported Languages as well.");
                }

                var newLang2 = (SystemLanguage)EditorGUILayout.EnumPopup(new GUIContent("Default Language", "This language will be used if the user's current language is not supported."), _sounds.defaultLanguage);
                if (newLang2 != _sounds.defaultLanguage) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Default Language");
                    _sounds.defaultLanguage = newLang2;
                }

                var newMode = (MasterAudio.LanguageMode)EditorGUILayout.EnumPopup("Language Mode", _sounds.langMode);
                if (newMode != _sounds.langMode) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Language Mode");
                    _sounds.langMode = newMode;
                    AudioResourceOptimizer.ClearSupportLanguageFolder();
                }

                if (_sounds.langMode == MasterAudio.LanguageMode.SpecificLanguage) {
                    var newLang = (SystemLanguage)EditorGUILayout.EnumPopup(new GUIContent("Use Specific Language", "This language will be used instead of your computer's setting. This is useful for testing other languages."), _sounds.testLanguage);
                    if (newLang != _sounds.testLanguage) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Use Specific");
                        _sounds.testLanguage = newLang;
                        AudioResourceOptimizer.ClearSupportLanguageFolder();
                    }

                    if (_sounds.supportedLanguages.Contains(_sounds.testLanguage)) {
                        DTGUIHelper.ShowLargeBarAlert("Please select your Specific Language under Supported Languages as well.");
                        DTGUIHelper.ShowLargeBarAlert("If you do not, it will use your Default Language instead.");
                    }
                } else if (_sounds.langMode == MasterAudio.LanguageMode.DynamicallySet) {
                    DTGUIHelper.ShowLargeBarAlert("Dynamic Language currently set to: " + MasterAudio.DynamicLanguage.ToString());
                }
            }
            DTGUIHelper.EndGroupedControls();
        }

        // Advanced section Start
        DTGUIHelper.VerticalSpace(3);

        EditorGUI.indentLevel = 0;

        state = _sounds.showAdvancedSettings;
        text = "Advanced Settings";

        // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
        if (!state) {
            GUI.backgroundColor = DTGUIHelper.InactiveHeaderColor;
        } else {
            GUI.backgroundColor = DTGUIHelper.ActiveHeaderColor;
        }

        GUILayout.BeginHorizontal();

#if UNITY_3_5_7
        if (!state) {
            text += " (Click to expand)";
        }
#else
        text = "<b><size=11>" + text + "</size></b>";
#endif
        if (state) {
            text = "\u25BC " + text;
        } else {
            text = "\u25BA " + text;
        }
        if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) {
            state = !state;
        }

        GUILayout.Space(2f);

        if (state != _sounds.showAdvancedSettings) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Advanced Settings");
            _sounds.showAdvancedSettings = state;
        }

        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/AdvancedSettings.htm");

        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        if (_sounds.showAdvancedSettings) {
            DTGUIHelper.BeginGroupedControls();
            if (!Application.isPlaying) {
                var newPersist = EditorGUILayout.Toggle(new GUIContent("Persist Across Scenes", "Turn this on only if you need music or other sounds to play across Scene changes. If not, create a different Master Audio prefab in each Scene."), _sounds.persistBetweenScenes);
                if (newPersist != _sounds.persistBetweenScenes) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Persist Across Scenes");
                    _sounds.persistBetweenScenes = newPersist;
                }
            }

            if (_sounds.persistBetweenScenes && plControllerInScene) {
                DTGUIHelper.ShowColorWarning("Playlist Controller(s) will also persist between scenes!");
            }

#if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
            // no support
#else
            var newGap = EditorGUILayout.Toggle(new GUIContent("Gapless Music Switching", "Turn this option on if you need perfect gapless transitions between clips in your Playlists. For Resource Files, this will take more audio memory as 2 clips are generally loaded into memory at the same time, so only use it if you need to."), _sounds.useGaplessPlaylists);
            if (newGap != _sounds.useGaplessPlaylists) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Gapless Music Switching");
                _sounds.useGaplessPlaylists = newGap;
            }
#endif

            var newFollow = EditorGUILayout.Toggle(new GUIContent("Follow Audio Listener", "This option will make previewing sounds in both Edit and Play mode always audible because the Audio Sources in this game object will be at the same location as the Audio Listener."), _sounds.followAudioListener);
            if (newFollow != _sounds.followAudioListener) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Follow Audio Listener");
                _sounds.followAudioListener = newFollow;
            }

            var newSave = EditorGUILayout.Toggle(new GUIContent("Save Runtime Changes", "Turn this on if you want to do real time adjustments to the mix, Master Audio prefab, Groups and Playlist Controllers and have the changes stick after you stop playing."), _sounds.saveRuntimeChanges);
            if (newSave != _sounds.saveRuntimeChanges) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Save Runtime Changes");
                _sounds.saveRuntimeChanges = newSave;
                _persistChanges = newSave;
            }

            var newIgnore = EditorGUILayout.Toggle(new GUIContent("Ignore Time Scale", "Turn this option on only if you need to use EventSounds Start event at zero timescale or DelayBetweenSongs"), _sounds.ignoreTimeScale);
            if (newIgnore != _sounds.ignoreTimeScale) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Ignore Time Scale");
                _sounds.ignoreTimeScale = newIgnore;
            }

            DTGUIHelper.StartGroupHeader();
            EditorGUILayout.BeginHorizontal();
            var newAutoPrioritize = GUILayout.Toggle(_sounds.prioritizeOnDistance, new GUIContent(" Apply Distance Priority", "Turn this on to have Master Audio automatically assign Priority to all audio, based on distance from the Audio Listener. Playlist Controller and 2D sounds are unaffected."));
            if (newAutoPrioritize != _sounds.prioritizeOnDistance) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Prioritize By Distance");
                _sounds.prioritizeOnDistance = newAutoPrioritize;
            }

            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/AdvancedSettings.htm#DistancePriority");
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();

            if (_sounds.prioritizeOnDistance) {
                EditorGUI.indentLevel = 0;

                var reevalIndex = _sounds.rePrioritizeEverySecIndex;

                var evalTimes = new List<string>();
                foreach (var t in _reevaluatePriorityTimes) {
                    evalTimes.Add(t + " seconds");
                }

                var newRepri = EditorGUILayout.Popup("Reprioritize Time Gap", reevalIndex, evalTimes.ToArray());
                if (newRepri != reevalIndex) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Re-evaluate time");
                    _sounds.rePrioritizeEverySecIndex = newRepri;
                }

                var newContinual = EditorGUILayout.Toggle("Use Clip Age Priority", _sounds.useClipAgePriority);
                if (newContinual != _sounds.useClipAgePriority) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Use Clip Age Priority");
                    _sounds.useClipAgePriority = newContinual;
                }
            }
            EditorGUILayout.EndVertical();

            EditorGUI.indentLevel = 1;

            DTGUIHelper.AddSpaceForNonU5(2);

            DTGUIHelper.StartGroupHeader();

            EditorGUILayout.BeginHorizontal();
            var newVisual = DTGUIHelper.Foldout(_sounds.visualAdvancedExpanded, "Visual Settings");
            if (newVisual != _sounds.visualAdvancedExpanded) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Visual Settings");
                _sounds.visualAdvancedExpanded = newVisual;
            }
            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/AdvancedSettings.htm#VisualSettings");
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();

            if (_sounds.visualAdvancedExpanded) {
                EditorGUI.indentLevel = 0;

                var newGiz = EditorGUILayout.Toggle(new GUIContent("Show Variation Gizmos", "Turning this option on will show you where your Variation and Event Sounds components are in the Scene with an 'M' icon."), _sounds.showGizmos);
                if (newGiz != _sounds.showGizmos) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Show Variation Gizmos");
                    _sounds.showGizmos = newGiz;
                }

                var newWidth = (MasterAudio.MixerWidthMode)EditorGUILayout.EnumPopup("Inspector Width", _sounds.MixerWidth);
                if (newWidth != _sounds.MixerWidth) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Inspector Width");
                    _sounds.MixerWidth = newWidth;
                }

                if (_sounds.MixerWidth == MasterAudio.MixerWidthMode.Narrow) {
                    var showBus = EditorGUILayout.Toggle("Show Buses in Narrow", _sounds.busesShownInNarrow);
                    if (showBus != _sounds.busesShownInNarrow) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Show Buses in Narrow");
                        _sounds.busesShownInNarrow = showBus;
                    }
                }
            }
            EditorGUILayout.EndVertical();

            EditorGUI.indentLevel = 1;
            DTGUIHelper.AddSpaceForNonU5(2);
            DTGUIHelper.StartGroupHeader();
            EditorGUILayout.BeginHorizontal();
            var exp = DTGUIHelper.Foldout(_sounds.showFadingSettings, "Fading Settings");
            if (exp != _sounds.showFadingSettings) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Fading Settings");
                _sounds.showFadingSettings = exp;
            }
            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/AdvancedSettings.htm#FadingSettings");
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
            if (_sounds.showFadingSettings) {
                EditorGUI.indentLevel = 0;
                DTGUIHelper.ShowLargeBarAlert("Fading to zero volume on the following causes their audio to stop (if checked).");

                var newStop = EditorGUILayout.Toggle("Buses", _sounds.stopZeroVolumeBuses);
                if (newStop != _sounds.stopZeroVolumeBuses) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Buses Stop");
                    _sounds.stopZeroVolumeBuses = newStop;
                }

                newStop = EditorGUILayout.Toggle("Variations", _sounds.stopZeroVolumeVariations);
                if (newStop != _sounds.stopZeroVolumeVariations) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Variations Stop");
                    _sounds.stopZeroVolumeVariations = newStop;
                }

                newStop = EditorGUILayout.Toggle("Sound Groups", _sounds.stopZeroVolumeGroups);
                if (newStop != _sounds.stopZeroVolumeGroups) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Sound Groups Stop");
                    _sounds.stopZeroVolumeGroups = newStop;
                }

                newStop = EditorGUILayout.Toggle(new GUIContent("Playlist Controllers", "Automatic crossfading will not trigger stop."), _sounds.stopZeroVolumePlaylists);
                if (newStop != _sounds.stopZeroVolumePlaylists) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Playlist Controllers Stop");
                    _sounds.stopZeroVolumePlaylists = newStop;
                }
            }
            EditorGUILayout.EndVertical();

            EditorGUI.indentLevel = 1;
            DTGUIHelper.AddSpaceForNonU5(2);
            DTGUIHelper.StartGroupHeader();

            EditorGUILayout.BeginHorizontal();
            var newResource = DTGUIHelper.Foldout(_sounds.resourceAdvancedExpanded, "Resource File Settings");
            if (newResource != _sounds.resourceAdvancedExpanded) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Resource File Settings");
                _sounds.resourceAdvancedExpanded = newResource;
            }
            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/AdvancedSettings.htm#ResourceSettings");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.EndVertical();

            if (_sounds.resourceAdvancedExpanded) {
                EditorGUI.indentLevel = 0;
                if (MasterAudio.HasAsyncResourceLoaderFeature()) {
                    var newAsync = EditorGUILayout.Toggle(new GUIContent("Always Load Res. Async", "Checking this means that you will not have this control per Sound Group or Playlist. All Resource files will be loaded asynchronously."), _sounds.resourceClipsAllLoadAsync);
                    if (newAsync != _sounds.resourceClipsAllLoadAsync) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Always Load Resources Async");
                        _sounds.resourceClipsAllLoadAsync = newAsync;
                    }
                }

                var newResourcePause = EditorGUILayout.Toggle(new GUIContent("Keep Paused Resources", "If you check this box, Resource files will not be automatically unloaded from memory when you pause them. Use at your own risk!"), _sounds.resourceClipsPauseDoNotUnload);
                if (newResourcePause != _sounds.resourceClipsPauseDoNotUnload) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Keep Paused Resources");
                    _sounds.resourceClipsPauseDoNotUnload = newResourcePause;
                }
            }
            EditorGUILayout.EndVertical();

            EditorGUI.indentLevel = 1;
            DTGUIHelper.AddSpaceForNonU5(2);
            DTGUIHelper.StartGroupHeader();
            EditorGUILayout.BeginHorizontal();
            var newLog = DTGUIHelper.Foldout(_sounds.logAdvancedExpanded, "Logging Settings");
            if (newLog != _sounds.logAdvancedExpanded) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Logging Settings");
                _sounds.logAdvancedExpanded = newLog;
            }
            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/AdvancedSettings.htm#LoggingSettings");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.EndVertical();

            if (_sounds.logAdvancedExpanded) {
                EditorGUI.indentLevel = 0;
                newLog = EditorGUILayout.Toggle("Disable Logging", _sounds.disableLogging);
                if (newLog != _sounds.disableLogging) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Disable Logging");
                    _sounds.disableLogging = newLog;
                }

                if (!_sounds.disableLogging) {
                    newLog = EditorGUILayout.Toggle("Log Sounds", _sounds.LogSounds);
                    if (newLog != _sounds.LogSounds) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Log Sounds");
                        if (Application.isPlaying) {
                            MasterAudio.LogSoundsEnabled = _sounds.LogSounds;
                        }
                        _sounds.LogSounds = newLog;
                    }

                    newLog = EditorGUILayout.Toggle("Log Custom Events", _sounds.logCustomEvents);
                    if (newLog != _sounds.logCustomEvents) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Log Custom Events");
                        _sounds.logCustomEvents = newLog;
                    }
                } else {
                    DTGUIHelper.ShowLargeBarAlert("Logging is disabled.");
                }
            }
            EditorGUILayout.EndVertical();

            DTGUIHelper.EndGroupedControls();
        }

        DTGUIHelper.ResetColors();
        // Music Ducking Start

        DTGUIHelper.VerticalSpace(3);

        EditorGUI.indentLevel = 0;

        state = _sounds.showMusicDucking;
        text = "Music Ducking";

        // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
        if (!state) {
            GUI.backgroundColor = DTGUIHelper.InactiveHeaderColor;
        } else {
            GUI.backgroundColor = DTGUIHelper.ActiveHeaderColor;
        }

        GUILayout.BeginHorizontal();

#if UNITY_3_5_7
        if (!state) {
            text += " (Click to expand)";
        }
#else
        text = "<b><size=11>" + text + "</size></b>";
#endif
        if (state) {
            text = "\u25BC " + text;
        } else {
            text = "\u25BA " + text;
        }
        if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) {
            state = !state;
        }

        GUILayout.Space(2f);

        if (state != _sounds.showMusicDucking) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Show Music Ducking");
            _sounds.showMusicDucking = state;
        }

        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/MusicDucking.htm");

        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        if (_sounds.showMusicDucking) {
            DTGUIHelper.BeginGroupedControls();
            var newEnableDuck = EditorGUILayout.BeginToggleGroup("Enable Ducking", _sounds.EnableMusicDucking);
            if (newEnableDuck != _sounds.EnableMusicDucking) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Enable Ducking");
                _sounds.EnableMusicDucking = newEnableDuck;
            }

            EditorGUILayout.Separator();

            var newMult = EditorGUILayout.Slider("Default Ducked Vol Cut", _sounds.defaultDuckedVolumeCut, DTGUIHelper.MinDb, DTGUIHelper.MaxDb);
            if (newMult != _sounds.defaultDuckedVolumeCut) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Default Ducked Vol Cut");
                _sounds.defaultDuckedVolumeCut = newMult;
            }

            var newDefault = EditorGUILayout.Slider("Default Unduck Time", _sounds.defaultUnduckTime, 0f, 5f);
            if (newDefault != _sounds.defaultUnduckTime) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Default Unduck Time");
                _sounds.defaultUnduckTime = newDefault;
            }

			newDefault = EditorGUILayout.Slider("Default Begin Unduck", _sounds.defaultRiseVolStart, 0f, 1f);
			if (newDefault != _sounds.defaultRiseVolStart) {
				AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Default Begin Unduck");
				_sounds.defaultRiseVolStart = newDefault;
			}

            GUI.contentColor = DTGUIHelper.BrightButtonColor;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(10);

            if (GUILayout.Button(new GUIContent("Add Duck Group"), EditorStyles.toolbarButton, GUILayout.Width(100))) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "Add Duck Group");
                _sounds.musicDuckingSounds.Add(new DuckGroupInfo() {
                    soundType = MasterAudio.NoGroupName,
                    riseVolStart = _sounds.defaultRiseVolStart,
                    duckedVolumeCut = _sounds.defaultDuckedVolumeCut,
                    unduckTime = _sounds.defaultUnduckTime
                });
            }

            EditorGUILayout.EndHorizontal();
            GUI.contentColor = Color.white;
            EditorGUILayout.Separator();

            if (_sounds.musicDuckingSounds.Count == 0) {
                DTGUIHelper.ShowLargeBarAlert("You currently have no ducking sounds set up.");
            } else {
                int? duckSoundToRemove = null;

                var spacerWidth = _sounds.MixerWidth == MasterAudio.MixerWidthMode.Wide ? 60 : 0;

                if (_sounds.musicDuckingSounds.Count > 0) {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label("Sound Group", EditorStyles.boldLabel);
                    GUILayout.FlexibleSpace();
                    GUILayout.Label(new GUIContent("Vol. Cut (dB)", "Amount to duck the music volume."), EditorStyles.boldLabel);
                    GUILayout.Space(6 + spacerWidth);
                    GUILayout.Label(new GUIContent("Beg. Unduck", "Begin Unducking after this amount of the sound has been played."), EditorStyles.boldLabel);
                    GUILayout.Space(13 + spacerWidth);
                    GUILayout.Label(new GUIContent("Unduck Time", "Unducking will take X seconds."), EditorStyles.boldLabel);
                    GUILayout.Space(54 + spacerWidth);
                    EditorGUILayout.EndHorizontal();
                }

                var slidWidth = _sounds.MixerWidth == MasterAudio.MixerWidthMode.Wide ? 120 : 60;

                for (var i = 0; i < _sounds.musicDuckingSounds.Count; i++) {
                    var duckSound = _sounds.musicDuckingSounds[i];
                    var index = groupNameList.IndexOf(duckSound.soundType);
                    if (index == -1) {
                        index = 0;
                    }

                    DTGUIHelper.StartGroupHeader();

                    EditorGUILayout.BeginHorizontal();
                    var newIndex = EditorGUILayout.Popup(index, groupNameList.ToArray(), GUILayout.MaxWidth(200));
                    if (newIndex >= 0) {
                        if (index != newIndex) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Duck Group");
                        }
                        duckSound.soundType = groupNameList[newIndex];
                    }

                    GUILayout.FlexibleSpace();

                    GUI.contentColor = DTGUIHelper.BrightButtonColor;
                    GUILayout.TextField(duckSound.duckedVolumeCut.ToString("N1"), 20, EditorStyles.miniLabel);

                    var newDuckMult = GUILayout.HorizontalSlider(duckSound.duckedVolumeCut, DTGUIHelper.MinDb, DTGUIHelper.MaxDb, GUILayout.Width(slidWidth));
                    if (newDuckMult != duckSound.duckedVolumeCut) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Ducked Vol Cut");
                        duckSound.duckedVolumeCut = newDuckMult;
                    }
                    GUI.contentColor = Color.white;

                    GUI.contentColor = DTGUIHelper.BrightButtonColor;
                    GUILayout.TextField(duckSound.riseVolStart.ToString("N2"), 20, EditorStyles.miniLabel);

                    var newUnduck = GUILayout.HorizontalSlider(duckSound.riseVolStart, 0f, 1f, GUILayout.Width(slidWidth));
                    if (newUnduck != duckSound.riseVolStart) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Begin Unduck");
                        duckSound.riseVolStart = newUnduck;
                    }
                    GUI.contentColor = Color.white;

                    GUILayout.Space(4);
                    GUILayout.TextField(duckSound.unduckTime.ToString("N2"), 20, EditorStyles.miniLabel);
                    var newTime = GUILayout.HorizontalSlider(duckSound.unduckTime, 0f, 5f, GUILayout.Width(slidWidth));
                    if (newTime != duckSound.unduckTime) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Unduck Time");
                        duckSound.unduckTime = newTime;
                    }

                    GUILayout.Space(10);
                    if (DTGUIHelper.AddDeleteIcon("Duck Sound")) {
                        duckSoundToRemove = i;
                    }

                    EditorGUILayout.EndHorizontal();
                    DTGUIHelper.EndGroupHeader();
                    DTGUIHelper.AddSpaceForNonU5(2);
                }

                if (duckSoundToRemove.HasValue) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "delete Duck Group");
                    _sounds.musicDuckingSounds.RemoveAt(duckSoundToRemove.Value);
                }

            }
            EditorGUILayout.EndToggleGroup();

            DTGUIHelper.EndGroupedControls();
        }
        // Music Ducking End

        DTGUIHelper.ResetColors();
        // Sound Groups Start		
        EditorGUI.indentLevel = 0;  // Space will handle this for the header
        DTGUIHelper.VerticalSpace(3);

        state = _sounds.areGroupsExpanded;
        text = "Group Mixer";

        // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
        if (!state) {
            GUI.backgroundColor = DTGUIHelper.InactiveHeaderColor;
        } else {
            GUI.backgroundColor = DTGUIHelper.ActiveHeaderColor;
        }

        GUILayout.BeginHorizontal();

#if UNITY_3_5_7
        if (!state) {
            text += " (Click to expand)";
        }
#else
        text = "<b><size=11>" + text + "</size></b>";
#endif
        if (state) {
            text = "\u25BC " + text;
        } else {
            text = "\u25BA " + text;
        }
        if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) {
            state = !state;
        }

        GUILayout.Space(2f);

        if (state != _sounds.areGroupsExpanded) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Group Mixer");
            _sounds.areGroupsExpanded = state;
        }

        GUI.color = Color.white;
        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/GroupMixer.htm");

        EditorGUILayout.EndHorizontal();

        GameObject groupToDelete = null;
        // ReSharper disable once TooWideLocalVariableScope
        // ReSharper disable once RedundantAssignment
        var audSrcTemplateIndex = -1;
        var applyTemplateToAll = false;

        if (_sounds.areGroupsExpanded) {
            DTGUIHelper.BeginGroupedControls();

            EditorGUI.indentLevel = 1;

            DTGUIHelper.StartGroupHeader();
            EditorGUILayout.BeginHorizontal();

            var newShow = DTGUIHelper.Foldout(_sounds.showGroupCreation, "Group Creation");
            if (newShow != _sounds.showGroupCreation) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Group Creation");
                _sounds.showGroupCreation = !_sounds.showGroupCreation;
            }
            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/GroupMixer.htm#GroupCreation");
            EditorGUILayout.EndHorizontal();

            GUI.contentColor = Color.white;
            EditorGUILayout.EndVertical();

            if (_sounds.showGroupCreation) {
                EditorGUI.indentLevel = 0;
                var groupTemplateIndex = -1;

                if (_sounds.audioSourceTemplates.Count > 0 && !Application.isPlaying && _sounds.showGroupCreation && _sounds.transform.childCount > 0) {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(10);
                    GUI.contentColor = DTGUIHelper.BrightButtonColor;
                    if (GUILayout.Button("Apply Audio Source Template to All", EditorStyles.toolbarButton, GUILayout.Width(190))) {
                        applyTemplateToAll = true;
                    }
                    GUI.contentColor = Color.white;
                    EditorGUILayout.EndHorizontal();
                }

                var newTemp = EditorGUILayout.Toggle("Use Group Templates", _sounds.useGroupTemplates);
                if (newTemp != _sounds.useGroupTemplates) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Use Group Templates");
                    _sounds.useGroupTemplates = newTemp;
                }

                if (_sounds.useGroupTemplates) {
                    _groupTemplateNames = new List<string>();

                    foreach (var temp in _sounds.groupTemplates) {
                        if (temp == null) {
                            continue;
                        }
                        _groupTemplateNames.Add(temp.name);
                    }

                    var templatesMissing = false;

                    if (Directory.Exists(MasterAudio.GroupTemplateFolder)) {
                        var grpTemplates = Directory.GetFiles(MasterAudio.GroupTemplateFolder, "*.prefab").Length;
                        if (grpTemplates > _sounds.groupTemplates.Count) {
                            templatesMissing = true;
                            DTGUIHelper.ShowLargeBarAlert("There are " + (grpTemplates - _sounds.groupTemplates.Count) + " Group Template(s) that aren't set up in this MA prefab. Locate them in Plugins/DarkTonic/MasterAudio/Sources/Prefabs/GroupTemplates and drag them in below.");
                        }
                    }

                    if (templatesMissing) {
                        // create groups start
                        EditorGUILayout.BeginVertical();
                        var aEvent = Event.current;

                        GUI.color = DTGUIHelper.DragAreaColor;

                        var dragArea = GUILayoutUtility.GetRect(0f, 35f, GUILayout.ExpandWidth(true));
                        GUI.Box(dragArea, "Drag prefabs here from Project View to create Group Templates!");

                        GUI.color = Color.white;

                        switch (aEvent.type) {
                            case EventType.DragUpdated:
                            case EventType.DragPerform:
                                if (!dragArea.Contains(aEvent.mousePosition)) {
                                    break;
                                }

                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                                if (aEvent.type == EventType.DragPerform) {
                                    DragAndDrop.AcceptDrag();

                                    foreach (var dragged in DragAndDrop.objectReferences) {
                                        var temp = dragged as GameObject;
                                        if (temp == null) {
                                            continue;
                                        }

                                        AddGroupTemplate(temp);
                                    }
                                }
                                Event.current.Use();
                                break;
                        }
                        EditorGUILayout.EndVertical();
                        // create groups end
                    }

                    if (_groupTemplateNames.Count == 0) {
                        DTGUIHelper.ShowRedError("You cannot create Groups without Templates. Drag them in or disable Group Templates.");
                    } else {
                        groupTemplateIndex = _groupTemplateNames.IndexOf(_sounds.groupTemplateName);
                        if (groupTemplateIndex < 0) {
                            groupTemplateIndex = 0;
                            _sounds.groupTemplateName = _groupTemplateNames[0];
                        }

                        var newIndex = EditorGUILayout.Popup("Group Template", groupTemplateIndex, _groupTemplateNames.ToArray());
                        if (newIndex != groupTemplateIndex) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Group Template");
                            _sounds.groupTemplateName = _groupTemplateNames[newIndex];
                        }
                    }
                }

                _audioSourceTemplateNames = new List<string>();

                foreach (var temp in _sounds.audioSourceTemplates) {
                    if (temp == null) {
                        continue;
                    }
                    _audioSourceTemplateNames.Add(temp.name);
                }

                var audTemplatesMissing = false;

                if (Directory.Exists(MasterAudio.AudioSourceTemplateFolder)) {
                    var audioSrcTemplates = Directory.GetFiles(MasterAudio.AudioSourceTemplateFolder, "*.prefab").Length;
                    if (audioSrcTemplates > _sounds.audioSourceTemplates.Count) {
                        audTemplatesMissing = true;
                        DTGUIHelper.ShowLargeBarAlert("There are " + (audioSrcTemplates - _sounds.audioSourceTemplates.Count) + " Audio Source Template(s) that aren't set up in this MA prefab. Locate them in Plugins/DarkTonic/MasterAudio/Sources/Prefabs/AudioSourceTemplates and drag them in below.");
                    }
                }

                if (audTemplatesMissing) {
                    // create groups start
                    EditorGUILayout.BeginVertical();
                    var aEvent = Event.current;

                    GUI.color = DTGUIHelper.DragAreaColor;

                    var dragArea = GUILayoutUtility.GetRect(0f, 35f, GUILayout.ExpandWidth(true));
                    GUI.Box(dragArea, "Drag prefabs here from Project View to create Audio Source Templates!");

                    GUI.color = Color.white;

                    switch (aEvent.type) {
                        case EventType.DragUpdated:
                        case EventType.DragPerform:
                            if (!dragArea.Contains(aEvent.mousePosition)) {
                                break;
                            }

                            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                            if (aEvent.type == EventType.DragPerform) {
                                DragAndDrop.AcceptDrag();

                                foreach (var dragged in DragAndDrop.objectReferences) {
                                    var temp = dragged as GameObject;
                                    if (temp == null) {
                                        continue;
                                    }

                                    AddAudioSourceTemplate(temp);
                                }
                            }
                            Event.current.Use();
                            break;
                    }
                    EditorGUILayout.EndVertical();
                    // create groups end
                }

                if (_audioSourceTemplateNames.Count == 0) {
                    DTGUIHelper.ShowRedError("You have no Audio Source Templates. Drag them in to create them.");
                } else {
                    audSrcTemplateIndex = _audioSourceTemplateNames.IndexOf(_sounds.audioSourceTemplateName);
                    if (audSrcTemplateIndex < 0) {
                        audSrcTemplateIndex = 0;
                        _sounds.audioSourceTemplateName = _audioSourceTemplateNames[0];
                    }

                    var newIndex = EditorGUILayout.Popup("Audio Source Template", audSrcTemplateIndex, _audioSourceTemplateNames.ToArray());
                    if (newIndex != audSrcTemplateIndex) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Audio Source Template");
                        _sounds.audioSourceTemplateName = _audioSourceTemplateNames[newIndex];
                    }
                }

                if (_sounds.useGroupTemplates) {
                    DTGUIHelper.ShowColorWarning("Bulk Creation Mode is ONE GROUP PER CLIP when using Group Templates.");
                } else {
                    var newGroupMode = (MasterAudio.DragGroupMode)EditorGUILayout.EnumPopup("Bulk Creation Mode", _sounds.curDragGroupMode);
                    if (newGroupMode != _sounds.curDragGroupMode) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Bulk Creation Mode");
                        _sounds.curDragGroupMode = newGroupMode;
                    }
                }

                var newBulkMode = DTGUIHelper.GetRestrictedAudioLocation("Variation Create Mode", _sounds.bulkLocationMode);
                if (newBulkMode != _sounds.bulkLocationMode) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Bulk Variation Mode");
                    _sounds.bulkLocationMode = newBulkMode;
                }

                if (_sounds.bulkLocationMode == MasterAudio.AudioLocation.ResourceFile) {
                    DTGUIHelper.ShowColorWarning("Resource mode: make sure to drag from Resource folders only.");
                }

                var cannotCreateGroups = _sounds.useGroupTemplates && _sounds.groupTemplates.Count == 0;
                MasterAudioGroup createdGroup = null;

                if (!cannotCreateGroups) {
                    // create groups start
                    var anEvent = Event.current;

                    var useGroupTemplate = _sounds.useGroupTemplates && groupTemplateIndex > -1;

                    if (!allowPreview) {
                        DTGUIHelper.ShowLargeBarAlert("You are in Project View and cannot create or navigate Groups.");
                        DTGUIHelper.ShowRedError("Create this prefab from Master Audio Manager window. Do not drag into Scene!");
                    } else {
                        GUI.color = DTGUIHelper.DragAreaColor;
                        EditorGUILayout.BeginVertical();
                        var dragArea = GUILayoutUtility.GetRect(0f, 35f, GUILayout.ExpandWidth(true));
                        GUI.Box(dragArea, "Drag Audio clips here to create Groups!");

                        GUI.color = Color.white;

                        switch (anEvent.type) {
                            case EventType.DragUpdated:
                            case EventType.DragPerform:
                                if (!dragArea.Contains(anEvent.mousePosition)) {
                                    break;
                                }

                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                                if (anEvent.type == EventType.DragPerform) {
                                    DragAndDrop.AcceptDrag();

                                    Transform groupTrans = null;

                                    foreach (var dragged in DragAndDrop.objectReferences) {
                                        var aClip = dragged as AudioClip;
                                        if (aClip == null) {
                                            continue;
                                        }

                                        if (useGroupTemplate) {
                                            createdGroup = CreateSoundGroupFromTemplate(aClip, groupTemplateIndex);
                                            continue;
                                        }

                                        if (_sounds.curDragGroupMode == MasterAudio.DragGroupMode.OneGroupPerClip) {
                                            CreateSoundGroup(aClip);
                                        } else {
                                            if (groupTrans == null) { // one group with variations
                                                groupTrans = CreateSoundGroup(aClip);
                                            } else {
                                                CreateVariation(groupTrans, aClip);
                                                // create the variations
                                            }
                                        }
                                    }
                                }
                                Event.current.Use();
                                break;
                        }
                        EditorGUILayout.EndVertical();
                    }
                    // create groups end
                }

                if (createdGroup != null) {
                    MasterAudioGroupInspector.RescanChildren(createdGroup);
                }
            }
            EditorGUILayout.EndVertical();

            EditorGUI.indentLevel = 0;

            DTGUIHelper.AddSpaceForNonU5(2);
            DTGUIHelper.StartGroupHeader();
            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.LabelField("Group Control");
            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/GroupMixer.htm#GroupControl");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.EndVertical();

            DTGUIHelper.ResetColors();

#if UNITY_5
            DTGUIHelper.StartGroupHeader(1, false);

            var newSpatialType = (MasterAudio.AllMixerSpatialBlendType)EditorGUILayout.EnumPopup("Group Spatial Blend Rule", _sounds.mixerSpatialBlendType);
            if (newSpatialType != _sounds.mixerSpatialBlendType) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Group Spatial Blend Rule");
                _sounds.mixerSpatialBlendType = newSpatialType;

                if (Application.isPlaying) {
                    _sounds.SetSpatialBlendForMixer();
                } else {
                    SetSpatialBlendForGroupsEdit();
                }
            }

            switch (_sounds.mixerSpatialBlendType) {
                case MasterAudio.AllMixerSpatialBlendType.ForceAllToCustom:
                    DTGUIHelper.ShowLargeBarAlert(SpatialBlendSliderText);
                    var newBlend = EditorGUILayout.Slider("Group Spatial Blend", _sounds.mixerSpatialBlend, 0f, 1f);
                    if (newBlend != _sounds.mixerSpatialBlend) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Group Spatial Blend");
                        _sounds.mixerSpatialBlend = newBlend;
                        if (Application.isPlaying) {
                            _sounds.SetSpatialBlendForMixer();
                        } else {
                            SetSpatialBlendForGroupsEdit();
                        }
                    }
                    break;
                case MasterAudio.AllMixerSpatialBlendType.AllowDifferentPerGroup:
                    DTGUIHelper.ShowLargeBarAlert("Go to each Group's settings to change Spatial Blend. Defaults below are for new Groups.");

                    var newDefType = (MasterAudio.ItemSpatialBlendType)EditorGUILayout.EnumPopup("Default Blend Type", _sounds.newGroupSpatialType);
                    if (newDefType != _sounds.newGroupSpatialType) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Default Blend Type");
                        _sounds.newGroupSpatialType = newDefType;
                    }

                    if (_sounds.newGroupSpatialType == MasterAudio.ItemSpatialBlendType.ForceToCustom) {
                        newBlend = EditorGUILayout.Slider("Default Spatial Blend", _sounds.newGroupSpatialBlend, 0f, 1f);
                        if (newBlend != _sounds.newGroupSpatialBlend) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Default  Spatial Blend");
                            _sounds.newGroupSpatialBlend = newBlend;
                        }
                    }
                    break;
            }
            EditorGUILayout.EndVertical();
            DTGUIHelper.ResetColors();
#endif

            EditorGUI.indentLevel = 0;
            var newBusFilterIndex = -1;
            var busFilterActive = false;

            if (_sounds.groupBuses.Count > 0) {
                busFilterActive = true;
                var oldBusFilter = busFilterList.IndexOf(_sounds.busFilter);
                if (oldBusFilter == -1) {
                    oldBusFilter = 0;
                }

                newBusFilterIndex = EditorGUILayout.Popup("Bus Filter", oldBusFilter, busFilterList.ToArray());

                var newBusFilter = busFilterList[newBusFilterIndex];

                if (_sounds.busFilter != newBusFilter) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Bus Filter");
                    _sounds.busFilter = newBusFilter;
                }
            }

            if (groups.Count > 0) {
                var newUseTextGroupFilter = EditorGUILayout.Toggle("Use Text Group Filter", _sounds.useTextGroupFilter);
                if (newUseTextGroupFilter != _sounds.useTextGroupFilter) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Use Text Group Filter");
                    _sounds.useTextGroupFilter = newUseTextGroupFilter;
                }

                if (_sounds.useTextGroupFilter) {
                    EditorGUI.indentLevel = 1;

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(10);
                    GUILayout.Label("Text Group Filter", GUILayout.Width(140));
                    var newTextFilter = GUILayout.TextField(_sounds.textGroupFilter, GUILayout.Width(180));
                    if (newTextFilter != _sounds.textGroupFilter) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Text Group Filter");
                        _sounds.textGroupFilter = newTextFilter;
                    }
                    GUILayout.Space(10);
                    GUI.contentColor = DTGUIHelper.BrightButtonColor;
                    if (GUILayout.Button("Clear", EditorStyles.toolbarButton, GUILayout.Width(70))) {
                        _sounds.textGroupFilter = string.Empty;
                    }
                    GUI.contentColor = Color.white;
                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.Separator();
                }

                if (Application.isPlaying) {
                    var newHide = EditorGUILayout.Toggle("Filter Out Inactive", _sounds.hideGroupsWithNoActiveVars);
                    if (newHide != _sounds.hideGroupsWithNoActiveVars) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Filter Out Inactive");
                        _sounds.hideGroupsWithNoActiveVars = newHide;
                    }
                }
            }

            EditorGUI.indentLevel = 0;
            var groupButtonPressed = DTGUIHelper.DTFunctionButtons.None;

            MasterAudioGroup aGroup = null;
            var filteredGroups = new List<MasterAudioGroup>();

            filteredGroups.AddRange(groups);

            if (busFilterActive && !string.IsNullOrEmpty(_sounds.busFilter)) {
                if (newBusFilterIndex == 0) {
                    // no filter
                } else if (newBusFilterIndex == 1) {
                    filteredGroups.RemoveAll(delegate(MasterAudioGroup obj) {
                        return obj.busIndex != 0;
                    });
                } else {
                    filteredGroups.RemoveAll(delegate(MasterAudioGroup obj) {
                        return obj.busIndex != newBusFilterIndex;
                    });
                }
            }

            if (_sounds.useTextGroupFilter) {
                if (!string.IsNullOrEmpty(_sounds.textGroupFilter)) {
                    filteredGroups.RemoveAll(delegate(MasterAudioGroup obj) {
                        return !obj.transform.name.ToLower().Contains(_sounds.textGroupFilter.ToLower());
                    });
                }
            }

            if (Application.isPlaying && _sounds.hideGroupsWithNoActiveVars) {
                filteredGroups.RemoveAll(delegate(MasterAudioGroup obj) {
                    return obj.ActiveVoices == 0;
                });
            }

            var totalVoiceCount = 0;

            var selectAll = false;
            var deselectAll = false;
            var applyAudioSourceTemplate = false;

            var bulkSelectedGrps = new List<MasterAudioGroup>(filteredGroups.Count);

            if (groups.Count == 0) {
                DTGUIHelper.ShowLargeBarAlert("You currently have zero Sound Groups.");
            } else {
                var groupsFiltered = groups.Count - filteredGroups.Count;
                if (groupsFiltered > 0) {
                    DTGUIHelper.ShowLargeBarAlert(string.Format("{0}/{1} Group(s) filtered out.", groupsFiltered, groups.Count));
                }

                var allFilteredOut = groupsFiltered == groups.Count;

                if (_sounds.groupBuses.Count > 0 && !allFilteredOut) {
                    var newGroupByBus = EditorGUILayout.Toggle("Group by Bus", _sounds.groupByBus);
                    if (newGroupByBus != _sounds.groupByBus) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Group by Bus");
                        _sounds.groupByBus = newGroupByBus;
                    }
                }

                if (filteredGroups.Count > 0) {
                    var newSelectGrp = EditorGUILayout.Toggle("Bulk Group Changes", _sounds.showGroupSelect);
                    if (newSelectGrp != _sounds.showGroupSelect) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Bulk Group Changes");
                        _sounds.showGroupSelect = newSelectGrp;
                    }

                    if (_sounds.showGroupSelect) {
                        GUI.contentColor = DTGUIHelper.BrightButtonColor;
                        EditorGUILayout.BeginHorizontal();
                        GUILayout.Space(10);
                        if (GUILayout.Button("Select All", EditorStyles.toolbarButton, GUILayout.Width(80))) {
                            selectAll = true;
                        }
                        GUILayout.Space(10);
                        if (GUILayout.Button("Deselect All", EditorStyles.toolbarButton, GUILayout.Width(80))) {
                            deselectAll = true;
                        }

                        foreach (var t in filteredGroups) {
                            if (t.isSelected) {
                                bulkSelectedGrps.Add(t);
                            }
                        }

                        if (!Application.isPlaying && _audioSourceTemplateNames.Count > 0 && bulkSelectedGrps.Count > 0) {
                            GUILayout.Space(10);
                            GUI.contentColor = DTGUIHelper.BrightButtonColor;
                            if (GUILayout.Button("Apply Audio Source Template", EditorStyles.toolbarButton, GUILayout.Width(160))) {
                                applyAudioSourceTemplate = true;
                            }
                        }
                        EditorGUILayout.EndHorizontal();
                        GUI.contentColor = Color.white;

                        if (bulkSelectedGrps.Count > 0) {
                            DTGUIHelper.ShowLargeBarAlert("Bulk editing - adjustments to a selected mixer Group will affect all " + bulkSelectedGrps.Count + " selected Group(s).");
                        } else {
                            EditorGUILayout.Separator();
                        }
                    }
                }

                var isBulkMute = false;
                var isBulkSolo = false;
                float? bulkVolume = null;
                int? bulkBusIndex = null;

                int? busToCreate = null;

                DTGUIHelper.ResetColors();

                for (var l = 0; l < filteredGroups.Count; l++) {
                    EditorGUI.indentLevel = 0;
                    aGroup = filteredGroups[l];

                    var groupDirty = false;
                    var isBulkEdit = bulkSelectedGrps.Count > 0 && aGroup.isSelected;

                    var sType = string.Empty;
                    if (Application.isPlaying) {
                        sType = aGroup.name;
                    }

                    EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
                    var groupName = aGroup.name;

                    if (Application.isPlaying) {
                        var groupVoices = aGroup.ActiveVoices;
                        var totalVoices = aGroup.TotalVoices;

                        GUI.color = DTGUIHelper.BrightTextColor;

                        if (groupVoices == 0) {
                            GUI.contentColor = Color.white;
                            GUI.backgroundColor = Color.white;
                            GUI.color = DTGUIHelper.InactiveMixerGroupColor;
                        } else if (groupVoices >= totalVoices) {
                            GUI.contentColor = Color.red;
                            GUI.backgroundColor = Color.red;
                        }

                        if (GUILayout.Button(new GUIContent(string.Format("[{0}]", groupVoices), "Click to select Variations"), EditorStyles.toolbarButton)) {
                            SelectActiveVariationsInGroup(aGroup);
                        }
                        DTGUIHelper.ResetColors();

                        switch (aGroup.GroupLoadStatus) {
                            case MasterAudio.InternetFileLoadStatus.Loading:
                                GUILayout.Button(
                                    new GUIContent(MasterAudioInspectorResources.LoadingTexture,
                                        "Downloading 1 or more Internet Files"), EditorStyles.toolbarButton, GUILayout.Width(24));
                                break;
                            case MasterAudio.InternetFileLoadStatus.Failed:
                                GUILayout.Button(
                                    new GUIContent(MasterAudioInspectorResources.ErrorTexture,
                                        "1 or more Internet Files failed download"), EditorStyles.toolbarButton, GUILayout.Width(24));
                                break;
                            case MasterAudio.InternetFileLoadStatus.Loaded:
                                GUILayout.Button(
                                    new GUIContent(MasterAudioInspectorResources.ReadyTexture,
                                        "All audio is ready to play"), EditorStyles.toolbarButton, GUILayout.Width(24));
                                break;
                        }

                        totalVoiceCount += groupVoices;
                    }

                    if (_sounds.showGroupSelect) {
                        var newChecked = EditorGUILayout.Toggle(aGroup.isSelected, EditorStyles.toggleGroup, GUILayout.Width(16));
                        if (newChecked != aGroup.isSelected) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref groupDirty, aGroup, "toggle Select Group");
                            aGroup.isSelected = newChecked;
                        }
                    }

                    var minWidth = 100;
                    if (_sounds.MixerWidth == MasterAudio.MixerWidthMode.Narrow) {
                        minWidth = NarrowWidth;
                    }

                    EditorGUILayout.LabelField(groupName, EditorStyles.label, GUILayout.MinWidth(minWidth));

                    GUILayout.FlexibleSpace();
                    EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(50));

                    if (_sounds.MixerWidth != MasterAudio.MixerWidthMode.Narrow || _sounds.busesShownInNarrow) {
                        // find bus.
                        var selectedBusIndex = aGroup.busIndex == -1 ? 0 : aGroup.busIndex;

                        GUI.contentColor = Color.white;
                        GUI.color = DTGUIHelper.BrightButtonColor;

                        var busIndex = EditorGUILayout.Popup("", selectedBusIndex, busList.ToArray(),
                            GUILayout.Width(busListWidth));
                        if (busIndex == -1) {
                            busIndex = 0;
                        }

                        if (aGroup.busIndex != busIndex && busIndex != 1) {
                            if (isBulkEdit) {
                                bulkBusIndex = busIndex;
                            } else {
                                AudioUndoHelper.RecordObjectPropertyForUndo(ref groupDirty, aGroup, "change Group Bus");
                            }
                        }

                        if (busIndex != 1 && !isBulkEdit) {
                            // don't change the index, so undo will work.
                            aGroup.busIndex = busIndex;
                        }

                        GUI.color = Color.white;

                        if (selectedBusIndex != busIndex) {
                            if (busIndex == 0 && Application.isPlaying) {
#if UNITY_5
                                _sounds.RouteGroupToUnityMixerGroup(sType, null);
#endif
                            } else if (busIndex == 1) {
                                busToCreate = l;
                                if (Application.isPlaying) {
#if UNITY_5
                                    _sounds.RouteGroupToUnityMixerGroup(sType, null);
#endif
                                }
                            } else if (busIndex >= MasterAudio.HardCodedBusOptions) {
                                var newBus = _sounds.groupBuses[busIndex - MasterAudio.HardCodedBusOptions];
                                if (Application.isPlaying) {
                                    var statGroup = MasterAudio.GrabGroup(sType);
                                    statGroup.busIndex = busIndex;

                                    if (newBus.isMuted) {
                                        MasterAudio.MuteGroup(aGroup.name);
                                    } else if (newBus.isSoloed) {
                                        MasterAudio.SoloGroup(aGroup.name);
                                    }

                                    // reassign Unity Mixer Group
#if UNITY_5
                                    _sounds.RouteGroupToUnityMixerGroup(sType, newBus.mixerChannel);
#endif
                                } else {
                                    // check if bus soloed or muted.
                                    if (newBus.isMuted) {
                                        aGroup.isMuted = true;
                                        aGroup.isSoloed = false;
                                    } else if (newBus.isSoloed) {
                                        aGroup.isMuted = false;
                                        aGroup.isSoloed = true;
                                    }
                                }
                            }
                        }
                    }

                    GUI.contentColor = DTGUIHelper.BrightTextColor;

                    if (_sounds.MixerWidth != MasterAudio.MixerWidthMode.Narrow) {
                        GUILayout.TextField(
                            DTGUIHelper.DisplayVolumeNumber(aGroup.groupMasterVolume, sliderIndicatorChars),
                            sliderIndicatorChars, EditorStyles.miniLabel, GUILayout.Width(sliderWidth));
                    }

                    var newVol = DTGUIHelper.DisplayVolumeField(aGroup.groupMasterVolume, DTGUIHelper.VolumeFieldType.MixerGroup, _sounds.MixerWidth);
                    if (newVol != aGroup.groupMasterVolume) {
                        if (isBulkEdit) {
                            bulkVolume = newVol;
                        } else {
                            SetMixerGroupVolume(aGroup, ref groupDirty, newVol, false);
                        }
                    }

                    GUI.contentColor = Color.white;
                    DTGUIHelper.AddLedSignalLight(_sounds, groupName);

                    groupButtonPressed = DTGUIHelper.AddMixerButtons(aGroup, "Group");

                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.EndHorizontal();

                    switch (groupButtonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Find:
                            DTGUIHelper.ShowFilteredRelationsGraph(aGroup.name);
                            break;
                        case DTGUIHelper.DTFunctionButtons.Play:
                            if (Application.isPlaying) {
                                MasterAudio.PlaySoundAndForget(aGroup.name);
                            } else {
                                var rndIndex = Random.Range(0, aGroup.groupVariations.Count);
                                var rndVar = aGroup.groupVariations[rndIndex];

                                var calcVolume = aGroup.groupMasterVolume * rndVar.VarAudio.volume;

                                if (rndVar.audLocation == MasterAudio.AudioLocation.ResourceFile) {
                                    StopPreviewer();
                                    var fileName = AudioResourceOptimizer.GetLocalizedFileName(rndVar.useLocalization, rndVar.resourceFileName);
                                    GetPreviewer().PlayOneShot(Resources.Load(fileName) as AudioClip, calcVolume);
                                } else {
                                    rndVar.VarAudio.PlayOneShot(rndVar.VarAudio.clip, calcVolume);
                                }

                                _isDirty = true;
                            }
                            break;
                        case DTGUIHelper.DTFunctionButtons.Stop:
                            if (Application.isPlaying) {
                                MasterAudio.StopAllOfSound(aGroup.name);
                            } else {
                                var hasResourceFile = false;
                                foreach (var t in aGroup.groupVariations) {
                                    t.VarAudio.Stop();
                                    if (t.audLocation == MasterAudio.AudioLocation.ResourceFile) {
                                        hasResourceFile = true;
                                    }
                                }

                                if (hasResourceFile) {
                                    StopPreviewer();
                                }
                            }
                            break;
                        case DTGUIHelper.DTFunctionButtons.Mute:
                            if (isBulkEdit) {
                                isBulkMute = true;
                            } else {
                                MuteMixerGroup(aGroup, ref groupDirty, false, false);
                            }
                            break;
                        case DTGUIHelper.DTFunctionButtons.Solo:
                            if (isBulkEdit) {
                                isBulkSolo = true;
                            } else {
                                SoloMixerGroup(aGroup, ref groupDirty, false, false);
                            }
                            break;
                        case DTGUIHelper.DTFunctionButtons.Go:
                            Selection.activeObject = aGroup.transform;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            groupToDelete = aGroup.transform.gameObject;
                            break;
                    }

                    if (groupDirty) {
                        EditorUtility.SetDirty(aGroup);
                    }
                }

                if (isBulkMute) {
                    AudioUndoHelper.RecordObjectsForUndo(bulkSelectedGrps.ToArray(), "Bulk Mute");

                    var wasWarningShown = false;

                    foreach (var grp in bulkSelectedGrps) {
                        wasWarningShown = MuteMixerGroup(grp, ref fakeDirty, true, wasWarningShown);
                        EditorUtility.SetDirty(grp);
                    }
                }

                if (isBulkSolo) {
                    AudioUndoHelper.RecordObjectsForUndo(bulkSelectedGrps.ToArray(), "Bulk Solo");

                    var wasWarningShown = false;

                    foreach (var grp in bulkSelectedGrps) {
                        wasWarningShown = SoloMixerGroup(grp, ref fakeDirty, true, wasWarningShown);
                        EditorUtility.SetDirty(grp);
                    }
                }

                if (bulkVolume.HasValue) {
                    AudioUndoHelper.RecordObjectsForUndo(bulkSelectedGrps.ToArray(), "Bulk Volume Adjustment");

                    foreach (var grp in bulkSelectedGrps) {
                        SetMixerGroupVolume(grp, ref fakeDirty, bulkVolume.Value, true);
                        EditorUtility.SetDirty(grp);
                    }
                }

                if (bulkBusIndex.HasValue) {
                    AudioUndoHelper.RecordObjectsForUndo(bulkSelectedGrps.ToArray(), "Bulk Bus Assignment");


                    foreach (var grp in bulkSelectedGrps) {
                        grp.busIndex = bulkBusIndex.Value;
#if UNITY_5
                        if (bulkBusIndex.Value == 0) {
                            _sounds.RouteGroupToUnityMixerGroup(grp.name, null);
                        } else {
                            var theBus = _sounds.groupBuses[bulkBusIndex.Value - MasterAudio.HardCodedBusOptions];
                            if (theBus != null) {
                                _sounds.RouteGroupToUnityMixerGroup(grp.name, theBus.mixerChannel);
                            }
                        }
#endif

                        EditorUtility.SetDirty(grp);
                    }
                }

                if (busToCreate.HasValue) {
                    CreateBus(busToCreate.Value);
                }

                if (groupToDelete != null) {
                    _sounds.musicDuckingSounds.RemoveAll(delegate(DuckGroupInfo obj) {
                        return obj.soundType == groupToDelete.name;
                    });
                    AudioUndoHelper.DestroyForUndo(groupToDelete);
                }

                if (Application.isPlaying) {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(9);
                    GUI.color = DTGUIHelper.BrightTextColor;
                    EditorGUILayout.LabelField(string.Format("[{0}] Total Active Voices", totalVoiceCount));
                    GUI.color = Color.white;
                    EditorGUILayout.EndHorizontal();
                }

                EditorGUILayout.Separator();
                EditorGUILayout.BeginHorizontal();

                if (_sounds.MixerWidth != MasterAudio.MixerWidthMode.Narrow) {
                    GUILayout.Space(10);
                }

                GUI.contentColor = DTGUIHelper.BrightButtonColor;
                if (GUILayout.Button(new GUIContent("Mute/Solo Reset", "Turn off all group mute and solo switches"), EditorStyles.toolbarButton, GUILayout.Width(100))) {
                    AudioUndoHelper.RecordObjectsForUndo(groups.ToArray(), "Mute/Solo Reset");

                    foreach (var t in groups) {
                        aGroup = t;
                        aGroup.isSoloed = false;
                        aGroup.isMuted = false;
                    }
                }

                GUILayout.Space(6);

                if (GUILayout.Button(new GUIContent("Max Grp. Volumes", "Reset all group volumes to full"), EditorStyles.toolbarButton, GUILayout.Width(104))) {
                    AudioUndoHelper.RecordObjectsForUndo(groups.ToArray(), "Max Grp. Volumes");

                    foreach (var t in groups) {
                        aGroup = t;
                        aGroup.groupMasterVolume = 1f;
                    }
                }

                GUI.contentColor = Color.white;

                EditorGUILayout.EndHorizontal();

                if (_sounds.MixerWidth == MasterAudio.MixerWidthMode.Narrow) {
                    DTGUIHelper.ShowColorWarning("Some controls are hidden from the Group Mixer in narrow mode.");
                }
            }

            if (selectAll) {
                AudioUndoHelper.RecordObjectsForUndo(filteredGroups.ToArray(), "Select Groups");

                foreach (var myGroup in filteredGroups) {
                    myGroup.isSelected = true;
                }
            }
            if (deselectAll) {
                AudioUndoHelper.RecordObjectsForUndo(filteredGroups.ToArray(), "Deselect Groups");

                foreach (var myGroup in filteredGroups) {
                    myGroup.isSelected = false;
                }
            }
            if (applyAudioSourceTemplate) {
                AudioUndoHelper.RecordObjectsForUndo(filteredGroups.ToArray(), "Apply Audio Source Template");

                foreach (var myGroup in filteredGroups) {
                    if (!myGroup.isSelected) {
                        continue;
                    }

                    for (var v = 0; v < myGroup.transform.childCount; v++) {
#if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
                        Debug.LogError("This feature requires Unity 4 or higher.");
#else
                        var aVar = myGroup.transform.GetChild(v);
                        var oldAudio = aVar.GetComponent<AudioSource>();
                        CopyFromAudioSourceTemplate(oldAudio, true);
#endif
                    }
                }
            }

            if (applyTemplateToAll) {
                AudioUndoHelper.RecordObjectsForUndo(filteredGroups.ToArray(), "Apply Audio Source Template to All");

                foreach (var myGroup in filteredGroups) {
                    for (var v = 0; v < myGroup.transform.childCount; v++) {
#if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
                        Debug.LogError("This feature requires Unity 4 or higher.");
#else
                        var aVar = myGroup.transform.GetChild(v);
                        var oldAudio = aVar.GetComponent<AudioSource>();
                        CopyFromAudioSourceTemplate(oldAudio, true);
#endif
                    }
                }
            }
            EditorGUILayout.EndVertical();
            // Sound Groups End

            // Buses
            if (_sounds.groupBuses.Count > 0) {
                DTGUIHelper.VerticalSpace(3);

                var voiceLimitedBuses = _sounds.groupBuses.FindAll(delegate(GroupBus obj) {
                    return obj.voiceLimit >= 0;
                });

                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("Bus Control", GUILayout.Width(74));
                if (voiceLimitedBuses.Count > 0) {
                    GUILayout.FlexibleSpace();
                    GUILayout.Label("Stop Oldest", GUILayout.Width(100));
                    var endSpace = 284;
                    switch (_sounds.MixerWidth) {
                        case MasterAudio.MixerWidthMode.Wide:
                            endSpace = 488;
                            break;
                        case MasterAudio.MixerWidthMode.Narrow:
                            endSpace = 214;
                            break;
                    }
                    GUILayout.Space(endSpace);
                }
                DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/GroupMixer.htm#BusMixer", true);
                EditorGUILayout.EndHorizontal();

                GroupBus aBus = null;
                var busButtonPressed = DTGUIHelper.DTFunctionButtons.None;
                int? busToDelete = null;
                int? busToSolo = null;
                int? busToMute = null;
                int? busToStop = null;

                for (var i = 0; i < _sounds.groupBuses.Count; i++) {
                    aBus = _sounds.groupBuses[i];

                    DTGUIHelper.StartGroupHeader(1, false);

                    if (_sounds.ShouldShowUnityAudioMixerGroupAssignments) {
                        EditorGUILayout.BeginVertical();
                        EditorGUILayout.BeginHorizontal();
                    } else {
                        EditorGUILayout.BeginHorizontal();
                    }

                    GUI.color = Color.gray;

                    if (Application.isPlaying) {
                        GUI.color = DTGUIHelper.BrightTextColor;
                        if (aBus.BusVoiceLimitReached) {
                            GUI.contentColor = Color.red;
                            GUI.backgroundColor = Color.red;
                        }
                        if (GUILayout.Button(string.Format("[{0:D2}]", aBus.ActiveVoices), EditorStyles.toolbarButton)) {
                            SelectActiveVariationsInBus(aBus);
                        }
                        DTGUIHelper.ResetColors();
                    }

                    GUI.color = Color.white;
                    var nameWidth = 170;
                    if (_sounds.MixerWidth == MasterAudio.MixerWidthMode.Narrow) {
                        nameWidth = NarrowWidth;
                    }

                    var newBusName = EditorGUILayout.TextField("", aBus.busName, GUILayout.MinWidth(nameWidth));
                    if (newBusName != aBus.busName) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Bus Name");
                        aBus.busName = newBusName;
                    }

                    GUILayout.FlexibleSpace();
                    if (voiceLimitedBuses.Contains(aBus)) {
                        GUI.color = DTGUIHelper.BrightButtonColor;
                        var newMono = GUILayout.Toggle(aBus.stopOldest, new GUIContent("", "Checking this box will make it so when the voice limit is already reached and you play a sound, the oldest sound will first be stopped."));
                        if (newMono != aBus.stopOldest) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Stop Oldest");
                            aBus.stopOldest = newMono;
                        }
                    }

                    GUI.color = Color.white;
                    GUILayout.Label("Voices");

                    GUI.color = DTGUIHelper.BrightButtonColor;
                    var oldLimitIndex = busVoiceLimitList.IndexOf(aBus.voiceLimit.ToString());
                    if (oldLimitIndex == -1) {
                        oldLimitIndex = 0;
                    }
                    var busVoiceLimitIndex = EditorGUILayout.Popup("", oldLimitIndex, busVoiceLimitList.ToArray(), GUILayout.MaxWidth(70));
                    if (busVoiceLimitIndex != oldLimitIndex) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Bus Voice Limit");
                        aBus.voiceLimit = busVoiceLimitIndex <= 0 ? -1 : busVoiceLimitIndex;
                    }

                    GUI.color = Color.white;

                    EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(50));

                    if (_sounds.MixerWidth != MasterAudio.MixerWidthMode.Narrow) {
                        GUI.color = DTGUIHelper.BrightTextColor;
                        GUILayout.TextField(DTGUIHelper.DisplayVolumeNumber(aBus.volume, sliderIndicatorChars),
                            sliderIndicatorChars, EditorStyles.miniLabel, GUILayout.Width(sliderWidth));
                    }

                    GUI.color = Color.white;
                    var newBusVol = DTGUIHelper.DisplayVolumeField(aBus.volume, DTGUIHelper.VolumeFieldType.Bus, _sounds.MixerWidth);
                    if (newBusVol != aBus.volume) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Bus Volume");
                        aBus.volume = newBusVol;
                        if (Application.isPlaying) {
                            MasterAudio.SetBusVolumeByName(aBus.busName, aBus.volume);
                        }
                    }

                    GUI.contentColor = Color.white;

                    busButtonPressed = DTGUIHelper.AddMixerBusButtons(aBus);

                    switch (busButtonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            busToDelete = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Solo:
                            busToSolo = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Mute:
                            busToMute = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Stop:
                            busToStop = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Find:
                            DTGUIHelper.ShowFilteredRelationsGraph(null, aBus.busName);
                            break;
                    }

                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.EndHorizontal();

#if UNITY_5
                    if (_sounds.ShouldShowUnityAudioMixerGroupAssignments) {
                        var newChan = (AudioMixerGroup)EditorGUILayout.ObjectField(aBus.mixerChannel, typeof(AudioMixerGroup), false);
                        if (newChan != aBus.mixerChannel) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Bus Mixer Group");
                            aBus.mixerChannel = newChan;
                            _sounds.RouteBusToUnityMixerGroup(aBus.busName, newChan);
                        }
                        EditorGUILayout.EndVertical();
                    }

                    if (_sounds.mixerSpatialBlendType != MasterAudio.AllMixerSpatialBlendType.ForceAllTo2D) {
                        var new2D = GUILayout.Toggle(aBus.forceTo2D, "Force to 2D");
                        if (new2D != aBus.forceTo2D) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Force to 2D");
                            aBus.forceTo2D = new2D;
                        }
                    }

#endif
                    EditorGUILayout.EndVertical();
                    DTGUIHelper.AddSpaceForNonU5(2);
                }

                if (busToDelete.HasValue) {
                    DeleteBus(busToDelete.Value);
                }
                if (busToMute.HasValue) {
                    MuteBus(busToMute.Value);
                }
                if (busToSolo.HasValue) {
                    SoloBus(busToSolo.Value);
                }
                if (busToStop.HasValue) {
                    MasterAudio.StopBus(_sounds.groupBuses[busToStop.Value].busName);
                }

                if (Application.isPlaying) {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(9);
                    GUI.color = DTGUIHelper.BrightTextColor;
                    EditorGUILayout.LabelField(string.Format("[{0:D2}] Total Active Voices", totalVoiceCount));
                    GUI.color = Color.white;
                    EditorGUILayout.EndHorizontal();
                }

                EditorGUILayout.Separator();
                EditorGUILayout.BeginHorizontal();
                GUILayout.Space(10);
                GUI.contentColor = DTGUIHelper.BrightButtonColor;
                GUI.backgroundColor = Color.white;

                if (GUILayout.Button(new GUIContent("Mute/Solo Reset", "Turn off all bus mute and solo switches"), EditorStyles.toolbarButton, GUILayout.Width(100))) {
                    BusMuteSoloReset();
                }

                GUILayout.Space(6);

                if (GUILayout.Button(new GUIContent("Max Bus Volumes", "Reset all bus volumes to full"), EditorStyles.toolbarButton, GUILayout.Width(100))) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "Max Bus Volumes");

                    foreach (var t in _sounds.groupBuses) {
                        aBus = t;
                        aBus.volume = 1f;
                    }
                }

#if UNITY_5
                GUILayout.Space(6);

                GUI.contentColor = DTGUIHelper.BrightButtonColor;
                var buttonText = "Show Unity Mixer Groups";
                if (_sounds.showUnityMixerGroupAssignment) {
                    buttonText = "Hide Unity Mixer Groups";
                }
                if (GUILayout.Button(new GUIContent(buttonText), EditorStyles.toolbarButton, GUILayout.Width(140))) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, buttonText);
                    _sounds.showUnityMixerGroupAssignment = !_sounds.showUnityMixerGroupAssignment;
                }
#endif

                GUI.contentColor = Color.white;
                EditorGUILayout.EndHorizontal();
            }

            DTGUIHelper.EndGroupedControls();
        }
        // Sound Buses End

        // Music playlist Start		
        DTGUIHelper.VerticalSpace(3);
        EditorGUILayout.BeginHorizontal();
        EditorGUI.indentLevel = 0;  // Space will handle this for the header

        DTGUIHelper.ResetColors();


        state = _sounds.playListExpanded;
        text = "Playlist Settings";

        // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
        if (!state) {
            GUI.backgroundColor = DTGUIHelper.InactiveHeaderColor;
        } else {
            GUI.backgroundColor = DTGUIHelper.ActiveHeaderColor;
        }

        GUILayout.BeginHorizontal();

#if UNITY_3_5_7
        if (!state) {
            text += " (Click to expand)";
        }
#else
        text = "<b><size=11>" + text + "</size></b>";
#endif
        if (state) {
            text = "\u25BC " + text;
        } else {
            text = "\u25BA " + text;
        }
        if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) {
            state = !state;
        }

        GUILayout.Space(2f);

        var isExp = state;


        if (isExp != _sounds.playListExpanded) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Playlist Settings");
            _sounds.playListExpanded = isExp;
        }

        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/PlaylistSettings.htm");

        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        EditorGUILayout.EndHorizontal();


        if (_sounds.playListExpanded) {
            DTGUIHelper.BeginGroupedControls();

            if (_sounds.MixerWidth == MasterAudio.MixerWidthMode.Narrow) {
                DTGUIHelper.ShowColorWarning("Some controls are hidden from Playlist Control in narrow mode.");
            }

#if UNITY_5
            DTGUIHelper.StartGroupHeader(1, false);
            var newMusicSpatialType = (MasterAudio.AllMusicSpatialBlendType)EditorGUILayout.EnumPopup("Music Spatial Blend Rule", _sounds.musicSpatialBlendType);
            if (newMusicSpatialType != _sounds.musicSpatialBlendType) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Music Spatial Blend Rule");
                _sounds.musicSpatialBlendType = newMusicSpatialType;

                if (Application.isPlaying) {
                    SetSpatialBlendsForPlaylistControllers();
                } else {
                    SetSpatialBlendForPlaylistsEdit();
                }
            }

            switch (_sounds.musicSpatialBlendType) {
                case MasterAudio.AllMusicSpatialBlendType.ForceAllToCustom:
                    DTGUIHelper.ShowLargeBarAlert(SpatialBlendSliderText);
                    var newMusic3D = EditorGUILayout.Slider("Music Spatial Blend", _sounds.musicSpatialBlend, 0f, 1f);
                    if (newMusic3D != _sounds.musicSpatialBlend) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Music Spatial Blend");
                        _sounds.musicSpatialBlend = newMusic3D;
                        if (Application.isPlaying) {
                            SetSpatialBlendsForPlaylistControllers();
                        } else {
                            SetSpatialBlendForPlaylistsEdit();
                        }
                    }
                    break;
                case MasterAudio.AllMusicSpatialBlendType.AllowDifferentPerController:
                    DTGUIHelper.ShowLargeBarAlert("To set Spatial Blend, go to each Playlist Controller and change it there.");
                    break;
            }
            EditorGUILayout.EndVertical();

            EditorGUILayout.Separator();
#endif

            EditorGUI.indentLevel = 0;  // Space will handle this for the header
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Playlist Controller Setup", EditorStyles.miniBoldLabel, GUILayout.Width(130));

            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/PlaylistSettings.htm#PlaylistControllerSetup", true);
            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel = 0;
            DTGUIHelper.StartGroupHeader();
            EditorGUILayout.BeginHorizontal();
            const string labelText = "Name";
            labelWidth = 146;
            if (_sounds.MixerWidth == MasterAudio.MixerWidthMode.Narrow) {
                labelWidth = NarrowWidth;
            }
            EditorGUILayout.LabelField(labelText, EditorStyles.miniBoldLabel, GUILayout.Width(labelWidth));
            if (plControllerInScene) {
                GUILayout.FlexibleSpace();
                if (_sounds.MixerWidth != MasterAudio.MixerWidthMode.Narrow) {
                    EditorGUILayout.LabelField("Sync Grp.", EditorStyles.miniBoldLabel, GUILayout.Width(54));
                }
                EditorGUILayout.LabelField("Initial Playlist", EditorStyles.miniBoldLabel, GUILayout.Width(100));
                var endLength = 208;
                if (Application.isPlaying) {
                    endLength = 182;
                }
                if (_sounds.MixerWidth == MasterAudio.MixerWidthMode.Narrow) {
                    endLength -= 58;
                }

                GUILayout.Space(endLength - extraPlaylistLength);
            }
            EditorGUILayout.EndHorizontal();

            if (!plControllerInScene) {
                DTGUIHelper.ShowLargeBarAlert("There are no Playlist Controllers in the scene. Music will not play.");
            } else {
                int? indexToDelete = null;

                _playlistNames.Insert(0, MasterAudio.NoPlaylistName);

                var syncGroupList = new List<string>();
                for (var i = 0; i < 4; i++) {
                    syncGroupList.Add((i + 1).ToString());
                }
                syncGroupList.Insert(0, MasterAudio.NoGroupName);

                for (var i = 0; i < pcs.Count; i++) {
                    var controller = pcs[i];
                    DTGUIHelper.StartGroupHeader(1, false);

#if UNITY_5
                    EditorGUILayout.BeginVertical();
                    EditorGUILayout.BeginHorizontal();
#else
                    EditorGUILayout.BeginHorizontal();
#endif

                    GUILayout.Label(controller.name, _sounds.MixerWidth == MasterAudio.MixerWidthMode.Narrow ? GUILayout.MinWidth(NarrowWidth) : GUILayout.MinWidth(105));

                    GUILayout.FlexibleSpace();

                    var ctrlDirty = false;

                    if (_sounds.MixerWidth != MasterAudio.MixerWidthMode.Narrow) {
                        GUI.color = DTGUIHelper.BrightButtonColor;
                        var syncIndex = syncGroupList.IndexOf(controller.syncGroupNum.ToString());
                        if (syncIndex == -1) {
                            syncIndex = 0;
                        }
                        var newSync = EditorGUILayout.Popup("", syncIndex, syncGroupList.ToArray(), GUILayout.Width(55));
                        if (newSync != syncIndex) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref ctrlDirty, controller,
                                "change Controller Sync Group");
                            controller.syncGroupNum = newSync;
                        }
                    }

                    var origIndex = _playlistNames.IndexOf(controller.startPlaylistName);
                    var isCustomPlaylist = false;
                    if (origIndex == -1) {
                        if (string.IsNullOrEmpty(controller.startPlaylistName) || controller.startPlaylistName.StartsWith("[")) {
                            origIndex = 0;
                            controller.startPlaylistName = string.Empty;
                        } else {
                            isCustomPlaylist = true;
                        }
                    }

                    if (isCustomPlaylist) {
                        EditorGUILayout.LabelField(controller.startPlaylistName, GUILayout.Width(playlistListWidth));
                    } else {
                        var newIndex = EditorGUILayout.Popup("", origIndex, _playlistNames.ToArray(),
                                GUILayout.Width(playlistListWidth));
                        if (newIndex != origIndex) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref ctrlDirty, controller,
                                "change Playlist Controller initial Playlist");
                            controller.startPlaylistName = _playlistNames[newIndex];
                        }
                    }
                    GUI.color = Color.white;

                    if (_sounds.MixerWidth != MasterAudio.MixerWidthMode.Narrow) {
                        GUI.contentColor = DTGUIHelper.BrightButtonColor;
                        GUILayout.TextField(
                            DTGUIHelper.DisplayVolumeNumber(controller._playlistVolume, sliderIndicatorChars),
                            sliderIndicatorChars, EditorStyles.miniLabel, GUILayout.Width(sliderWidth));
                    }
                    var newVol = DTGUIHelper.DisplayVolumeField(controller._playlistVolume, DTGUIHelper.VolumeFieldType.PlaylistController, _sounds.MixerWidth);

                    if (newVol != controller._playlistVolume) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref ctrlDirty, controller, "change Playlist Controller volume");
                        controller.PlaylistVolume = newVol;
                    }

                    GUI.contentColor = Color.white;

                    var buttonPressed = DTGUIHelper.AddPlaylistControllerSetupButtons(controller, "Playlist Controller", false);

                    EditorGUILayout.EndHorizontal();

#if UNITY_5
                    if (_sounds.showUnityMixerGroupAssignment) {
                        var newChan = (AudioMixerGroup)EditorGUILayout.ObjectField(controller.mixerChannel, typeof(AudioMixerGroup), false);
                        if (newChan != controller.mixerChannel) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref ctrlDirty, controller, "change Playlist Controller Unity Mixer Group");
                            controller.mixerChannel = newChan;

                            if (Application.isPlaying) {
                                controller.RouteToMixerChannel(newChan);
                            }
                        }
                    }

                    EditorGUILayout.EndVertical();
#endif

                    switch (buttonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Go:
                            Selection.activeObject = controller.transform;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            indexToDelete = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Mute:
                            controller.ToggleMutePlaylist();
                            ctrlDirty = true;
                            break;
                    }

                    EditorGUILayout.EndVertical();
                    DTGUIHelper.AddSpaceForNonU5(1);

                    if (ctrlDirty) {
                        EditorUtility.SetDirty(controller);
                    }
                }

                if (indexToDelete.HasValue) {
                    AudioUndoHelper.DestroyForUndo(pcs[indexToDelete.Value].gameObject);
                }
            }

            EditorGUILayout.Separator();
            GUI.contentColor = DTGUIHelper.BrightButtonColor;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(10);
            GUI.backgroundColor = Color.white;
            if (GUILayout.Button(new GUIContent("Create Playlist Controller"), EditorStyles.toolbarButton, GUILayout.Width(150))) {
                // ReSharper disable once RedundantCast
                var go = (GameObject)Instantiate(_sounds.playlistControllerPrefab.gameObject);
                go.name = "PlaylistController";

                AudioUndoHelper.CreateObjectForUndo(go, "create Playlist Controller");
            }

            var buttonText = string.Empty;

#if UNITY_5
            GUILayout.Space(6);
            GUI.contentColor = DTGUIHelper.BrightButtonColor;
            buttonText = "Show Unity Mixer Groups";
            if (_sounds.showUnityMixerGroupAssignment) {
                buttonText = "Hide Unity Mixer Groups";
            }
            if (GUILayout.Button(new GUIContent(buttonText), EditorStyles.toolbarButton, GUILayout.Width(140))) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, buttonText);
                _sounds.showUnityMixerGroupAssignment = !_sounds.showUnityMixerGroupAssignment;
            }
#endif

            EditorGUILayout.EndHorizontal();
            DTGUIHelper.EndGroupHeader();

            GUI.contentColor = Color.white;

            EditorGUILayout.Separator();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Playlist Setup", EditorStyles.miniBoldLabel, GUILayout.Width(80));
            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/PlaylistSettings.htm#PlaylistSetup", true);
            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel = 0;  // Space will handle this for the header

            if (_sounds.musicPlaylists.Count == 0) {
                DTGUIHelper.ShowLargeBarAlert("You currently have no Playlists set up.");
            }

            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            EditorGUI.indentLevel = 1;
            var oldPlayExpanded = DTGUIHelper.Foldout(_sounds.playlistsExpanded, string.Format("Playlists ({0})", _sounds.musicPlaylists.Count));
            if (oldPlayExpanded != _sounds.playlistsExpanded) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Playlists");
                _sounds.playlistsExpanded = oldPlayExpanded;
            }

            EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(100));

            var addPressed = false;

            buttonText = "Click to add new Playlist at the end";
            // Add button - Process presses later
            GUI.contentColor = DTGUIHelper.BrightButtonColor;
            addPressed = GUILayout.Button(new GUIContent("Add", buttonText),
                                               EditorStyles.toolbarButton);
            GUIContent content;
            GUI.contentColor = DTGUIHelper.BrightButtonColor;

            content = new GUIContent("Collapse", "Click to collapse all");
            var masterCollapse = GUILayout.Button(content, EditorStyles.toolbarButton);

            content = new GUIContent("Expand", "Click to expand all");
            var masterExpand = GUILayout.Button(content, EditorStyles.toolbarButton);
            if (masterExpand) {
                ExpandCollapseAllPlaylists(true);
            }
            if (masterCollapse) {
                ExpandCollapseAllPlaylists(false);
            }
            GUI.contentColor = Color.white;
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndHorizontal();

            if (_sounds.playlistsExpanded) {
                int? playlistToRemove = null;
                int? playlistToInsertAt = null;
                int? playlistToMoveUp = null;
                int? playlistToMoveDown = null;

                for (var i = 0; i < _sounds.musicPlaylists.Count; i++) {
                    var aList = _sounds.musicPlaylists[i];

                    DTGUIHelper.StartGroupHeader();

                    EditorGUI.indentLevel = 1;
                    EditorGUILayout.BeginHorizontal();
                    aList.isExpanded = DTGUIHelper.Foldout(aList.isExpanded, "Playlist: " + aList.playlistName);

                    var playlistButtonPressed = DTGUIHelper.AddFoldOutListItemButtonItems(i, _sounds.musicPlaylists.Count, "playlist", false, false, true);

                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.EndVertical();

                    if (aList.isExpanded) {
                        EditorGUI.indentLevel = 0;
                        var newPlaylist = EditorGUILayout.TextField("Name", aList.playlistName);
                        if (newPlaylist != aList.playlistName) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Name");
                            aList.playlistName = newPlaylist;
                        }

                        var crossfadeMode = (MasterAudio.Playlist.CrossfadeTimeMode)EditorGUILayout.EnumPopup("Crossfade Mode", aList.crossfadeMode);
                        if (crossfadeMode != aList.crossfadeMode) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Crossfade Mode");
                            aList.crossfadeMode = crossfadeMode;
                        }
                        if (aList.crossfadeMode == MasterAudio.Playlist.CrossfadeTimeMode.Override) {
                            var newCf = EditorGUILayout.Slider("Crossfade time (sec)", aList.crossFadeTime, 0f, MasterAudio.MaxCrossFadeTimeSeconds);
                            if (newCf != aList.crossFadeTime) {
                                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Crossfade time (sec)");
                                aList.crossFadeTime = newCf;
                            }
                        }

                        var newFadeIn = EditorGUILayout.Toggle("Fade In First Song", aList.fadeInFirstSong);
                        if (newFadeIn != aList.fadeInFirstSong) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Fade In First Song");
                            aList.fadeInFirstSong = newFadeIn;
                        }

                        var newFadeOut = EditorGUILayout.Toggle("Fade Out Last Song", aList.fadeOutLastSong);
                        if (newFadeOut != aList.fadeOutLastSong) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Fade Out Last Song");
                            aList.fadeOutLastSong = newFadeOut;
                        }

                        var newTransType = (MasterAudio.SongFadeInPosition)EditorGUILayout.EnumPopup("Song Transition Type", aList.songTransitionType);
                        if (newTransType != aList.songTransitionType) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Song Transition Type");
                            aList.songTransitionType = newTransType;
                        }
                        if (aList.songTransitionType == MasterAudio.SongFadeInPosition.SynchronizeClips) {
                            DTGUIHelper.ShowColorWarning("All clips must be of exactly the same length in this mode.");
                        }

                        EditorGUI.indentLevel = 0;
                        var newBulkMode = DTGUIHelper.GetRestrictedAudioLocation("Clip Create Mode", aList.bulkLocationMode);
                        if (newBulkMode != aList.bulkLocationMode) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Bulk Clip Mode");
                            aList.bulkLocationMode = newBulkMode;
                        }

                        var playlistHasResource = false;
                        foreach (var t in aList.MusicSettings) {
                            if (t.audLocation != MasterAudio.AudioLocation.ResourceFile) {
                                continue;
                            }

                            playlistHasResource = true;
                            break;
                        }

                        if (MasterAudio.HasAsyncResourceLoaderFeature() && playlistHasResource) {
                            if (!_sounds.resourceClipsAllLoadAsync) {
                                var newAsync = EditorGUILayout.Toggle(new GUIContent("Load Resources Async", "Checking this means Resource files in this Playlist will be loaded asynchronously."), aList.resourceClipsAllLoadAsync);
                                if (newAsync != aList.resourceClipsAllLoadAsync) {
                                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Load Resources Async");
                                    aList.resourceClipsAllLoadAsync = newAsync;
                                }
                            }
                        }

                        EditorGUILayout.BeginHorizontal();
                        GUILayout.Space(10);
                        GUI.contentColor = DTGUIHelper.BrightButtonColor;
                        if (GUILayout.Button(new GUIContent("Eq. Song Volumes"), EditorStyles.toolbarButton, GUILayout.Width(110))) {
                            EqualizePlaylistVolumes(aList.MusicSettings);
                        }

                        var hasExpanded = false;
                        foreach (var t in aList.MusicSettings) {
                            if (!t.isExpanded) {
                                continue;
                            }

                            hasExpanded = true;
                            break;
                        }

                        var theButtonText = hasExpanded ? "Collapse All" : "Expand All";

                        GUILayout.Space(10);
                        GUI.contentColor = DTGUIHelper.BrightButtonColor;
                        if (GUILayout.Button(new GUIContent(theButtonText), EditorStyles.toolbarButton, GUILayout.Width(76))) {
                            ExpandCollapseSongs(aList, !hasExpanded);
                        }
                        GUILayout.Space(10);
                        if (GUILayout.Button(new GUIContent("Sort Alpha"), EditorStyles.toolbarButton, GUILayout.Width(70))) {
                            SortSongsAlpha(aList);
                        }

                        GUILayout.FlexibleSpace();
                        EditorGUILayout.EndHorizontal();
                        GUI.contentColor = Color.white;
                        EditorGUILayout.Separator();

                        EditorGUILayout.BeginVertical();
                        var anEvent = Event.current;

                        GUI.color = DTGUIHelper.DragAreaColor;

                        var dragArea = GUILayoutUtility.GetRect(0f, 35f, GUILayout.ExpandWidth(true));
                        GUI.Box(dragArea, "Drag Audio clips here to add to playlist!");

                        GUI.color = Color.white;

                        switch (anEvent.type) {
                            case EventType.DragUpdated:
                            case EventType.DragPerform:
                                if (!dragArea.Contains(anEvent.mousePosition)) {
                                    break;
                                }

                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                                if (anEvent.type == EventType.DragPerform) {
                                    DragAndDrop.AcceptDrag();

                                    foreach (var dragged in DragAndDrop.objectReferences) {
                                        var aClip = dragged as AudioClip;
                                        if (aClip == null) {
                                            continue;
                                        }

                                        AddSongToPlaylist(aList, aClip);
                                    }
                                }
                                Event.current.Use();
                                break;
                        }
                        EditorGUILayout.EndVertical();

                        EditorGUI.indentLevel = 2;

                        int? addIndex = null;
                        int? removeIndex = null;
                        int? moveUpIndex = null;
                        int? moveDownIndex = null;
                        int? indexToClone = null;

                        if (aList.MusicSettings.Count == 0) {
                            EditorGUI.indentLevel = 0;
                            DTGUIHelper.ShowLargeBarAlert("You currently have no songs in this Playlist.");
                        }

                        EditorGUI.indentLevel = 0;
                        for (var j = 0; j < aList.MusicSettings.Count; j++) {
                            DTGUIHelper.StartGroupHeader(1);

                            var aSong = aList.MusicSettings[j];
                            var clipName = "Empty";
                            switch (aSong.audLocation) {
                                case MasterAudio.AudioLocation.Clip:
                                    if (aSong.clip != null) {
                                        clipName = aSong.clip.name;
                                    }
                                    break;
                                case MasterAudio.AudioLocation.ResourceFile:
                                    if (!string.IsNullOrEmpty(aSong.resourceFileName)) {
                                        clipName = aSong.resourceFileName;
                                    }
                                    break;
                            }
                            EditorGUILayout.BeginHorizontal();
                            EditorGUI.indentLevel = 1;

                            aSong.songName = aSong.alias;
                            if (!string.IsNullOrEmpty(clipName) && string.IsNullOrEmpty(aSong.songName)) {
                                switch (aSong.audLocation) {
                                    case MasterAudio.AudioLocation.Clip:
                                        aSong.songName = clipName;
                                        break;
                                    case MasterAudio.AudioLocation.ResourceFile:
                                        aSong.songName = clipName;
                                        break;
                                }
                            }

                            var newSongExpanded = DTGUIHelper.Foldout(aSong.isExpanded, aSong.songName);
                            if (newSongExpanded != aSong.isExpanded) {
                                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Song expand");
                                aSong.isExpanded = newSongExpanded;
                            }

                            var songButtonPressed = DTGUIHelper.AddFoldOutListItemButtonItems(j, aList.MusicSettings.Count, "clip", false, true, true, allowPreview);
                            GUILayout.Space(4);
                            DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/PlaylistSettings.htm#Song");
                            EditorGUILayout.EndHorizontal();
                            EditorGUILayout.EndVertical();

                            if (aSong.isExpanded) {
                                EditorGUI.indentLevel = 0;

                                var newName = EditorGUILayout.TextField(new GUIContent("Song Id (optional)", "When you 'Play song by name', Song Id's will be searched first before audio file name."), aSong.alias);
                                if (newName != aSong.alias) {
                                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Song Id");
                                    aSong.alias = newName;
                                }

                                var oldLocation = aSong.audLocation;
                                var newClipSource = DTGUIHelper.GetRestrictedAudioLocation("Audio Origin", aSong.audLocation);
                                if (newClipSource != aSong.audLocation) {
                                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Audio Origin");
                                    aSong.audLocation = newClipSource;
                                }

                                switch (aSong.audLocation) {
                                    case MasterAudio.AudioLocation.Clip:
                                        var newClip = (AudioClip)EditorGUILayout.ObjectField("Audio Clip", aSong.clip, typeof(AudioClip), true);
                                        if (newClip != aSong.clip) {
                                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Clip");
                                            aSong.clip = newClip;
                                            var cName = newClip == null ? "Empty" : newClip.name;
                                            aSong.songName = cName;
                                        }
                                        break;
                                    case MasterAudio.AudioLocation.ResourceFile:
                                        if (oldLocation != aSong.audLocation) {
                                            if (aSong.clip != null) {
                                                Debug.Log("Audio clip removed to prevent unnecessary memory usage on Resource file Playlist clip.");
                                            }
                                            aSong.clip = null;
                                            aSong.songName = string.Empty;
                                        }

                                        EditorGUILayout.BeginVertical();
                                        anEvent = Event.current;

                                        GUI.color = DTGUIHelper.DragAreaColor;
                                        dragArea = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
                                        GUI.Box(dragArea, "Drag Resource Audio clip here to use its name!");
                                        GUI.color = Color.white;

                                        switch (anEvent.type) {
                                            case EventType.DragUpdated:
                                            case EventType.DragPerform:
                                                if (!dragArea.Contains(anEvent.mousePosition)) {
                                                    break;
                                                }

                                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                                                if (anEvent.type == EventType.DragPerform) {
                                                    DragAndDrop.AcceptDrag();

                                                    foreach (var dragged in DragAndDrop.objectReferences) {
                                                        var aClip = dragged as AudioClip;
                                                        if (aClip == null) {
                                                            continue;
                                                        }

                                                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Resource Filename");

                                                        var unused = false;
                                                        var resourceFileName = DTGUIHelper.GetResourcePath(aClip, ref unused, true);
                                                        if (string.IsNullOrEmpty(resourceFileName)) {
                                                            resourceFileName = aClip.name;
                                                        }

                                                        aSong.resourceFileName = resourceFileName;
                                                        aSong.songName = aClip.name;
                                                    }
                                                }
                                                Event.current.Use();
                                                break;
                                        }
                                        EditorGUILayout.EndVertical();

                                        var newFilename = EditorGUILayout.TextField("Resource Filename", aSong.resourceFileName);
                                        if (newFilename != aSong.resourceFileName) {
                                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Resource Filename");
                                            aSong.resourceFileName = newFilename;
                                        }

                                        break;
                                }

                                var newVol = DTGUIHelper.DisplayVolumeField(aSong.volume, DTGUIHelper.VolumeFieldType.None, _sounds.MixerWidth, 0f, true);
                                if (newVol != aSong.volume) {
                                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Volume");
                                    aSong.volume = newVol;
                                }

                                var newPitch = DTGUIHelper.DisplayPitchField(aSong.pitch);
                                if (newPitch != aSong.pitch) {
                                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Pitch");
                                    aSong.pitch = newPitch;
                                }

                                var crossFadetime = MasterAudio.Instance.MasterCrossFadeTime;
                                if (aList.crossfadeMode == MasterAudio.Playlist.CrossfadeTimeMode.Override) {
                                    crossFadetime = aList.crossFadeTime;
                                }

                                if (aList.songTransitionType == MasterAudio.SongFadeInPosition.SynchronizeClips && crossFadetime > 0) {
                                    DTGUIHelper.ShowLargeBarAlert("All songs must loop in Synchronized Playlists when crossfade time is not zero. Auto-advance is disabled.");
                                } else {
                                    var newLoop = EditorGUILayout.Toggle("Loop Clip", aSong.isLoop);
                                    if (newLoop != aSong.isLoop) {
                                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Loop Clip");
                                        aSong.isLoop = newLoop;
                                    }
                                }

                                if (aList.songTransitionType == MasterAudio.SongFadeInPosition.NewClipFromBeginning) {
                                    var newStart = EditorGUILayout.FloatField("Start Time (seconds)", aSong.customStartTime, GUILayout.Width(300));
                                    if (newStart < 0) {
                                        newStart = 0f;
                                    }
                                    if (newStart != aSong.customStartTime) {
                                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Start Time (seconds)");
                                        aSong.customStartTime = newStart;
                                    }
                                }

                                GUI.color = Color.white;
                                var exp = EditorGUILayout.BeginToggleGroup(" Fire 'Song Started' Event", aSong.songStartedEventExpanded);
                                if (exp != aSong.songStartedEventExpanded) {
                                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle expand Fire 'Song Started' Event");
                                    aSong.songStartedEventExpanded = exp;
                                }
                                GUI.color = Color.white;

                                if (aSong.songStartedEventExpanded) {
                                    EditorGUI.indentLevel = 1;
                                    DTGUIHelper.ShowColorWarning("When song starts, fire Custom Event below.");

                                    var existingIndex = _sounds.CustomEventNames.IndexOf(aSong.songStartedCustomEvent);

                                    int? customEventIndex = null;

                                    var noEvent = false;
                                    var noMatch = false;

                                    if (existingIndex >= 1) {
                                        customEventIndex = EditorGUILayout.Popup("Custom Event Name", existingIndex, _sounds.CustomEventNames.ToArray());
                                        if (existingIndex == 1) {
                                            noEvent = true;
                                        }
                                    } else if (existingIndex == -1 && aSong.songStartedCustomEvent == MasterAudio.NoGroupName) {
                                        customEventIndex = EditorGUILayout.Popup("Custom Event Name", existingIndex, _sounds.CustomEventNames.ToArray());
                                    } else { // non-match
                                        noMatch = true;
                                        var newEventName = EditorGUILayout.TextField("Custom Event Name", aSong.songStartedCustomEvent);
                                        if (newEventName != aSong.songStartedCustomEvent) {
                                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Custom Event Name");
                                            aSong.songStartedCustomEvent = newEventName;
                                        }

                                        var newIndex = EditorGUILayout.Popup("All Custom Events", -1, _sounds.CustomEventNames.ToArray());
                                        if (newIndex >= 0) {
                                            customEventIndex = newIndex;
                                        }
                                    }

                                    if (noEvent) {
                                        DTGUIHelper.ShowRedError("No Custom Event specified. This section will do nothing.");
                                    } else if (noMatch) {
                                        DTGUIHelper.ShowRedError("Custom Event found no match. Type in or choose one.");
                                    }

                                    if (customEventIndex.HasValue) {
                                        if (existingIndex != customEventIndex.Value) {
                                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Custom Event");
                                        }
                                        // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                                        if (customEventIndex.Value == -1) {
                                            aSong.songStartedCustomEvent = MasterAudio.NoGroupName;
                                        } else {
                                            aSong.songStartedCustomEvent = _sounds.CustomEventNames[customEventIndex.Value];
                                        }
                                    }
                                }
                                EditorGUILayout.EndToggleGroup();

                                EditorGUI.indentLevel = 0;

                                if (_sounds.useGaplessPlaylists) {
                                    DTGUIHelper.ShowLargeBarAlert("Song Changed Event cannot be used with gapless transitions.");
                                } else {
                                    exp = EditorGUILayout.BeginToggleGroup(" Fire 'Song Changed' Event", aSong.songChangedEventExpanded);
                                    if (exp != aSong.songChangedEventExpanded) {
                                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle expand Fire 'Song Changed' Event");
                                        aSong.songChangedEventExpanded = exp;
                                    }
                                    GUI.color = Color.white;

                                    if (aSong.songChangedEventExpanded) {
                                        EditorGUI.indentLevel = 1;
                                        DTGUIHelper.ShowColorWarning("When song changes to another, fire Custom Event below.");

                                        var existingIndex = _sounds.CustomEventNames.IndexOf(aSong.songChangedCustomEvent);

                                        int? customEventIndex = null;

                                        var noEvent = false;
                                        var noMatch = false;

                                        if (existingIndex >= 1) {
                                            customEventIndex = EditorGUILayout.Popup("Custom Event Name", existingIndex, _sounds.CustomEventNames.ToArray());
                                            if (existingIndex == 1) {
                                                noEvent = true;
                                            }
                                        } else if (existingIndex == -1 && aSong.songChangedCustomEvent == MasterAudio.NoGroupName) {
                                            customEventIndex = EditorGUILayout.Popup("Custom Event Name", existingIndex, _sounds.CustomEventNames.ToArray());
                                        } else { // non-match
                                            noMatch = true;
                                            var newEventName = EditorGUILayout.TextField("Custom Event Name", aSong.songChangedCustomEvent);
                                            if (newEventName != aSong.songChangedCustomEvent) {
                                                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Custom Event Name");
                                                aSong.songChangedCustomEvent = newEventName;
                                            }

                                            var newIndex = EditorGUILayout.Popup("All Custom Events", -1, _sounds.CustomEventNames.ToArray());
                                            if (newIndex >= 0) {
                                                customEventIndex = newIndex;
                                            }
                                        }

                                        if (noEvent) {
                                            DTGUIHelper.ShowRedError("No Custom Event specified. This section will do nothing.");
                                        } else if (noMatch) {
                                            DTGUIHelper.ShowRedError("Custom Event found no match. Type in or choose one.");
                                        }

                                        if (customEventIndex.HasValue) {
                                            if (existingIndex != customEventIndex.Value) {
                                                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Custom Event");
                                            }
                                            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                                            if (customEventIndex.Value == -1) {
                                                aSong.songChangedCustomEvent = MasterAudio.NoGroupName;
                                            } else {
                                                aSong.songChangedCustomEvent = _sounds.CustomEventNames[customEventIndex.Value];
                                            }
                                        }
                                    }
                                    EditorGUILayout.EndToggleGroup();
                                }
                            }

                            switch (songButtonPressed) {
                                case DTGUIHelper.DTFunctionButtons.Add:
                                    addIndex = j;
                                    break;
                                case DTGUIHelper.DTFunctionButtons.Remove:
                                    removeIndex = j;
                                    break;
                                case DTGUIHelper.DTFunctionButtons.Clone:
                                    indexToClone = j;
                                    break;
                                case DTGUIHelper.DTFunctionButtons.ShiftUp:
                                    moveUpIndex = j;
                                    break;
                                case DTGUIHelper.DTFunctionButtons.ShiftDown:
                                    moveDownIndex = j;
                                    break;
                                case DTGUIHelper.DTFunctionButtons.Play:
                                    StopPreviewer();
                                    switch (aSong.audLocation) {
                                        case MasterAudio.AudioLocation.Clip:
                                            GetPreviewer().PlayOneShot(aSong.clip, aSong.volume);
                                            break;
                                        case MasterAudio.AudioLocation.ResourceFile:
                                            GetPreviewer().PlayOneShot(Resources.Load(aSong.resourceFileName) as AudioClip, aSong.volume);
                                            break;
                                    }
                                    break;
                                case DTGUIHelper.DTFunctionButtons.Stop:
                                    GetPreviewer().clip = null;
                                    StopPreviewer();
                                    break;
                            }
                            EditorGUILayout.EndVertical();
                            DTGUIHelper.AddSpaceForNonU5(2);
                        }

                        if (addIndex.HasValue) {
                            var mus = new MusicSetting();
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "add song");
                            aList.MusicSettings.Insert(addIndex.Value + 1, mus);
                        } else if (removeIndex.HasValue) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "delete song");
                            aList.MusicSettings.RemoveAt(removeIndex.Value);
                        } else if (moveUpIndex.HasValue) {
                            var item = aList.MusicSettings[moveUpIndex.Value];

                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "shift up song");

                            aList.MusicSettings.Insert(moveUpIndex.Value - 1, item);
                            aList.MusicSettings.RemoveAt(moveUpIndex.Value + 1);
                        } else if (moveDownIndex.HasValue) {
                            var index = moveDownIndex.Value + 1;
                            var item = aList.MusicSettings[index];

                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "shift down song");

                            aList.MusicSettings.Insert(index - 1, item);
                            aList.MusicSettings.RemoveAt(index + 1);
                        } else if (indexToClone.HasValue) {
                            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "clone song");
                            aList.MusicSettings.Insert(indexToClone.Value, MusicSetting.Clone(aList.MusicSettings[indexToClone.Value]));
                        }
                    }

                    switch (playlistButtonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            playlistToRemove = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Add:
                            playlistToInsertAt = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.ShiftUp:
                            playlistToMoveUp = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.ShiftDown:
                            playlistToMoveDown = i;
                            break;
                    }

                    EditorGUILayout.EndVertical();
                    DTGUIHelper.AddSpaceForNonU5(4);
                }

                if (playlistToRemove.HasValue) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "delete Playlist");
                    _sounds.musicPlaylists.RemoveAt(playlistToRemove.Value);
                }
                if (playlistToInsertAt.HasValue) {
                    var pl = new MasterAudio.Playlist();
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "add Playlist");
                    _sounds.musicPlaylists.Insert(playlistToInsertAt.Value + 1, pl);
                }
                if (playlistToMoveUp.HasValue) {
                    var item = _sounds.musicPlaylists[playlistToMoveUp.Value];
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "shift up Playlist");
                    _sounds.musicPlaylists.Insert(playlistToMoveUp.Value - 1, item);
                    _sounds.musicPlaylists.RemoveAt(playlistToMoveUp.Value + 1);
                }
                if (playlistToMoveDown.HasValue) {
                    var index = playlistToMoveDown.Value + 1;
                    var item = _sounds.musicPlaylists[index];

                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "shift down Playlist");

                    _sounds.musicPlaylists.Insert(index - 1, item);
                    _sounds.musicPlaylists.RemoveAt(index + 1);
                }
            }

            if (addPressed) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "add Playlist");
                _sounds.musicPlaylists.Add(new MasterAudio.Playlist());
            }

            DTGUIHelper.EndGroupedControls();
        }
        // Music playlist End

        // Custom Events Start
        EditorGUI.indentLevel = 0;
        DTGUIHelper.VerticalSpace(3);

        DTGUIHelper.ResetColors();

        state = _sounds.showCustomEvents;
        text = "Custom Events";

        // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
        if (!state) {
            GUI.backgroundColor = DTGUIHelper.InactiveHeaderColor;
        } else {
            GUI.backgroundColor = DTGUIHelper.ActiveHeaderColor;
        }

        GUILayout.BeginHorizontal();

#if UNITY_3_5_7
        if (!state) {
            text += " (Click to expand)";
        }
#else
        text = "<b><size=11>" + text + "</size></b>";
#endif
        if (state) {
            text = "\u25BC " + text;
        } else {
            text = "\u25BA " + text;
        }
        if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) {
            state = !state;
        }

        GUILayout.Space(2f);

        isExp = state;

        if (isExp != _sounds.showCustomEvents) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle Custom Events");
            _sounds.showCustomEvents = isExp;
        }
        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/CustomEvents.htm");

        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        if (_sounds.showCustomEvents) {
            DTGUIHelper.BeginGroupedControls();
            var newEvent = EditorGUILayout.TextField("New Event Name", _sounds.newEventName);
            if (newEvent != _sounds.newEventName) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change New Event Name");
                _sounds.newEventName = newEvent;
            }

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(10);
            GUI.contentColor = DTGUIHelper.BrightButtonColor;
            if (GUILayout.Button("Create New Event", EditorStyles.toolbarButton, GUILayout.Width(100))) {
                CreateCustomEvent(_sounds.newEventName);
            }
            GUILayout.Space(10);
            GUI.contentColor = DTGUIHelper.BrightButtonColor;

            var hasExpanded = false;
            foreach (var t in _sounds.customEvents) {
                if (!t.eventExpanded) {
                    continue;
                }
                hasExpanded = true;
                break;
            }

            var buttonText = hasExpanded ? "Collapse All" : "Expand All";

            if (GUILayout.Button(buttonText, EditorStyles.toolbarButton, GUILayout.Width(100))) {
                ExpandCollapseCustomEvents(!hasExpanded);
            }
            GUILayout.Space(10);
            if (GUILayout.Button("Sort Alpha", EditorStyles.toolbarButton, GUILayout.Width(100))) {
                SortCustomEvents();
            }

            GUI.contentColor = Color.white;
            EditorGUILayout.EndHorizontal();

            if (_sounds.customEvents.Count == 0) {
                DTGUIHelper.ShowLargeBarAlert("You currently have no Custom Events.");
            }

            int? customEventToDelete = null;
            int? eventToRename = null;

            for (var i = 0; i < _sounds.customEvents.Count; i++) {
                EditorGUI.indentLevel = 1;
                var anEvent = _sounds.customEvents[i];

                DTGUIHelper.AddSpaceForNonU5(2);
                DTGUIHelper.StartGroupHeader();

                EditorGUILayout.BeginHorizontal();
                var exp = DTGUIHelper.Foldout(anEvent.eventExpanded, anEvent.EventName);
                if (exp != anEvent.eventExpanded) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "toggle expand Custom Event");
                    anEvent.eventExpanded = exp;
                }

                GUILayout.FlexibleSpace();
                if (Application.isPlaying) {
                    var receivers = MasterAudio.ReceiversForEvent(anEvent.EventName);

                    GUI.contentColor = DTGUIHelper.BrightButtonColor;
                    if (receivers.Count > 0) {
                        if (GUILayout.Button(new GUIContent("Select", "Click this button to select all Receivers in the Hierarchy"), EditorStyles.toolbarButton, GUILayout.Width(50))) {
                            var matches = new List<GameObject>(receivers.Count);

                            foreach (var t in receivers) {
                                matches.Add(t.gameObject);
                            }
                            Selection.objects = matches.ToArray();
                        }
                    }

                    if (GUILayout.Button("Fire!", EditorStyles.toolbarButton, GUILayout.Width(50))) {
                        MasterAudio.FireCustomEvent(anEvent.EventName, _sounds.transform.position);
                    }

                    GUI.contentColor = DTGUIHelper.BrightButtonColor;
                    GUILayout.Label(string.Format("Receivers: {0}", receivers.Count));
                    GUI.contentColor = Color.white;
                } else {
                    var newName = GUILayout.TextField(anEvent.ProspectiveName, GUILayout.Width(170));
                    if (newName != anEvent.ProspectiveName) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Proposed Event Name");
                        anEvent.ProspectiveName = newName;
                    }

                    var buttonPressed = DTGUIHelper.AddDeleteIcon(true, "Custom Event");

                    switch (buttonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            customEventToDelete = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Rename:
                            eventToRename = i;
                            break;
                    }
                }

                EditorGUILayout.EndHorizontal();
                EditorGUILayout.EndVertical();

                if (!anEvent.eventExpanded) {
                    EditorGUILayout.EndVertical();
                    continue;
                }

                EditorGUI.indentLevel = 0;
                var rcvMode = (MasterAudio.CustomEventReceiveMode)EditorGUILayout.EnumPopup("Send To Receivers", anEvent.eventReceiveMode);
                if (rcvMode != anEvent.eventReceiveMode) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Send To Receivers");
                    anEvent.eventReceiveMode = rcvMode;
                }

                if (rcvMode == MasterAudio.CustomEventReceiveMode.WhenDistanceLessThan || rcvMode == MasterAudio.CustomEventReceiveMode.WhenDistanceMoreThan) {
                    var newDist = EditorGUILayout.Slider("Distance Threshold", anEvent.distanceThreshold, 0f, float.MaxValue);
                    if (newDist != anEvent.distanceThreshold) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref _isDirty, _sounds, "change Distance Threshold");
                        anEvent.distanceThreshold = newDist;
                    }
                }
                EditorGUILayout.EndVertical();
            }

            if (customEventToDelete.HasValue) {
                _sounds.customEvents.RemoveAt(customEventToDelete.Value);
            }
            if (eventToRename.HasValue) {
                RenameEvent(_sounds.customEvents[eventToRename.Value]);
            }

            DTGUIHelper.EndGroupedControls();
        }

        // Custom Events End

        if (GUI.changed || _isDirty) {
            EditorUtility.SetDirty(target);
        }

        //DrawDefaultInspector();
    }
    public static DTFunctionButtons AddMixerButtons(MasterAudioGroup aGroup, string itemName, MasterAudio sounds)
    {
        var deleteIcon = sounds.deleteTexture;
        var settingsIcon = sounds.settingsTexture;

        var muteContent = new GUIContent(sounds.muteOffTexture, "Click to mute " + itemName);

        if (aGroup.isMuted) {
            muteContent.image = sounds.muteOnTexture;
        }

        var soloContent = new GUIContent(sounds.soloOffTexture, "Click to solo " + itemName);

        if (aGroup.isSoloed) {
            soloContent.image = sounds.soloOnTexture;
        }

        if (GUILayout.Button(soloContent, EditorStyles.toolbarButton)) {
            return DTFunctionButtons.Solo;
        }
        if (GUILayout.Button(muteContent, EditorStyles.toolbarButton)) {
            return DTFunctionButtons.Mute;
        }

        if (GUILayout.Button(new GUIContent(settingsIcon, "Click to edit " + itemName), EditorStyles.toolbarButton)) {
            return DTFunctionButtons.Go;
        }

        if (GUILayout.Button(new GUIContent(sounds.playTexture, "Click to preview " + itemName), EditorStyles.toolbarButton)) {
            return DTFunctionButtons.Play;
        }
        if (GUILayout.Button(new GUIContent(sounds.stopTrackTexture, "Click to stop all of Sound"), EditorStyles.toolbarButton)) {
            return DTFunctionButtons.Stop;
        }

        if (!Application.isPlaying) {
            if (GUILayout.Button(new GUIContent(deleteIcon, "Click to delete " + itemName), EditorStyles.toolbarButton)) {
                return DTFunctionButtons.Remove;
            }
        }

        return DTFunctionButtons.None;
    }
    public static MasterAudio.AudioLocation GetRestrictedAudioLocation(string label, MasterAudio.AudioLocation currentLoc) {
        var options = new List<GUIContent>();

        var iEnum = Enum.GetNames(typeof(MasterAudio.AudioLocation)).GetEnumerator();

        var selIndex = 0;
        var i = 0;
        while (iEnum.MoveNext()) {
            // ReSharper disable once PossibleNullReferenceException
            if (iEnum.Current.ToString() == currentLoc.ToString()) {
                selIndex = i;
            }

            i++;

            if (iEnum.Current.ToString() == MasterAudio.AudioLocation.FileOnInternet.ToString()) {
                continue;
            }

            options.Add(new GUIContent(iEnum.Current.ToString(), iEnum.Current.ToString()));
        }

        var newIndex = EditorGUILayout.Popup(new GUIContent(label, label), selIndex, options.ToArray());
        var selEnum = (MasterAudio.AudioLocation)Enum.Parse(typeof(MasterAudio.AudioLocation), options[newIndex].text);

        return selEnum;
    }
    public static DTFunctionButtons AddPlaylistMuteButton(string itemName, MasterAudio sounds)
    {
        var muteContent = new GUIContent(sounds.muteOffTexture, "Click to mute " + itemName);

        if (sounds.playlistsMuted) {
            muteContent.image = sounds.muteOnTexture;
        }

        bool mutePressed = GUILayout.Button(muteContent, EditorStyles.toolbarButton);

        if (mutePressed == true) {
            return DTFunctionButtons.Mute;
        }

        return DTFunctionButtons.None;
    }
    public static float DisplayVolumeField(float vol, VolumeFieldType fieldType, MasterAudio.MixerWidthMode widthMode, float volumeMin = 0f, bool showFieldName = false, string fieldName = "Volume") {
        var wideMode = widthMode == MasterAudio.MixerWidthMode.Wide;
        var narrowMode = widthMode == MasterAudio.MixerWidthMode.Narrow;

        var forceToNonDb = MasterAudio.UseDbScaleForVolume && vol < 0;

        if (!MasterAudio.UseDbScaleForVolume || forceToNonDb) {
            switch (fieldType) {
                case VolumeFieldType.MixerGroup:
                    return GUILayout.HorizontalSlider(vol, 0f, 1f, GUILayout.Width(wideMode ? WideModeWidth : NormalModeWidth));
                case VolumeFieldType.DynamicMixerGroup:
                    return GUILayout.HorizontalSlider(vol, 0f, 1f, GUILayout.Width(100));
                case VolumeFieldType.Bus:
                    var width = wideMode ? WideModeWidth : NormalBusWidth;
                    if (narrowMode) {
                        width = NormalModeWidth;
                    }

                    return GUILayout.HorizontalSlider(vol, 0f, 1f, GUILayout.Width(width));
                case VolumeFieldType.PlaylistController:
                    var wid = 74;
                    if (narrowMode) {
                        wid = NormalModeWidth;
                    }
                    return GUILayout.HorizontalSlider(vol, 0f, 1f, GUILayout.Width(wid));
                case VolumeFieldType.None:
                    if (showFieldName) {
                        return EditorGUILayout.Slider(fieldName, vol, volumeMin, 1f);
                    }

                    return EditorGUILayout.Slider(vol, volumeMin, 1f, narrowMode ? GUILayout.Width(115) : GUILayout.Width(252));
                case VolumeFieldType.GlobalVolume:
                    if (showFieldName) {
                        return EditorGUILayout.Slider(fieldName, vol, volumeMin, 1f);
                    }

                    var newVol = GUILayout.HorizontalSlider(vol, volumeMin, 1f, narrowMode ? GUILayout.Width(61) : GUILayout.Width(198));
                    var newVol2 = EditorGUILayout.FloatField(vol, GUILayout.Width(50));
                    if (newVol > 1) {
                        newVol = 1;
                    }
                    if (newVol < 0) {
                        newVol = 0;
                    }
                    if (newVol != vol) {
                        return newVol;
                    }
                    return newVol2;
            }
        }

        var dbLevel = (float)Math.Round(AudioUtil.GetDbFromFloatVolume(vol), 1);

        var newDbLevel = 0f;
        switch (fieldType) {
            case VolumeFieldType.MixerGroup:
                newDbLevel = GUILayout.HorizontalSlider(dbLevel, MinDb, MaxDb, GUILayout.Width(wideMode ? WideModeWidth : NormalModeWidth));
                break;
            case VolumeFieldType.DynamicMixerGroup:
                newDbLevel = GUILayout.HorizontalSlider(dbLevel, MinDb, MaxDb, GUILayout.Width(100));
                break;
            case VolumeFieldType.Bus:
                var sliderWidth = wideMode ? WideModeWidth : NormalBusWidth;
                if (narrowMode) {
                    sliderWidth = NormalModeWidth;
                }

                newDbLevel = GUILayout.HorizontalSlider(dbLevel, MinDb, MaxDb, GUILayout.Width(sliderWidth));
                break;
            case VolumeFieldType.PlaylistController:
                var sliderWid = 74;
                if (narrowMode) {
                    sliderWid = NormalModeWidth;
                }
                newDbLevel = GUILayout.HorizontalSlider(dbLevel, MinDb, MaxDb, GUILayout.Width(sliderWid));
                break;
            case VolumeFieldType.None:
                // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                if (showFieldName) {
                    newDbLevel = EditorGUILayout.Slider(fieldName + DbText, dbLevel, MinDb, MaxDb);
                } else {
                    newDbLevel = EditorGUILayout.Slider(dbLevel, MinDb, MaxDb, narrowMode ? GUILayout.Width(115) : GUILayout.Width(252));
                }
                break;
            case VolumeFieldType.GlobalVolume:
                if (showFieldName) {
                    return EditorGUILayout.Slider(fieldName + DbText, dbLevel, MinDb, MaxDb);
                }

                newDbLevel = GUILayout.HorizontalSlider(dbLevel, MinDb, MaxDb, narrowMode ? GUILayout.Width(61) : GUILayout.Width(198));
                newDbLevel = EditorGUILayout.FloatField(newDbLevel, GUILayout.Width(50));
                if (newDbLevel > MaxDb) {
                    newDbLevel = MaxDb;
                }
                if (newDbLevel < MinDb) {
                    newDbLevel = MinDb;
                }
                break;
        }

        return AudioUtil.GetFloatVolumeFromDb(newDbLevel);
    }
 public static bool AddDeleteIcon(MasterAudio sounds)
 {
     var deleteIcon = sounds.deleteTexture;
     return GUILayout.Button(new GUIContent(deleteIcon, "Click to delete Duck Sound"), EditorStyles.toolbarButton, GUILayout.MaxWidth(30));
 }
    private void ScanGroups(MasterAudio sounds)
    {
        this.groups.Clear();

        var names = new List<string>();

        for (var i = 0; i < sounds.transform.childCount; i++) {
            var aChild = sounds.transform.GetChild(i);
            if (names.Contains(aChild.name)) {
                GUIHelper.ShowColorWarning("You have more than one group named '" + aChild.name + "'.");
                GUIHelper.ShowColorWarning("Please rename one of them before continuing.");
                isValid = false;
                return;
            }

            names.Add(aChild.name);
            this.groups.Add(aChild.GetComponent<MasterAudioGroup>());
        }

        if (sounds.groupByBus) {
            this.groups.Sort(delegate(MasterAudioGroup g1, MasterAudioGroup g2)     {
                if (g1.busIndex == g2.busIndex) {
                    return g1.name.CompareTo(g2.name);
                } else {
                    return g1.busIndex.CompareTo(g2.busIndex);
                }
            });
        } else {
            this.groups.Sort(delegate(MasterAudioGroup g1, MasterAudioGroup g2)     {
                return g1.name.CompareTo(g2.name);
            });
        }
    }
    private void AddSongToPlaylist(MasterAudio.Playlist pList, AudioClip aClip)
    {
        var lastClip = pList.MusicSettings[pList.MusicSettings.Count - 1];

        MusicSetting mus;

        UndoHelper.RecordObjectPropertyForUndo(sounds, "add Song");

        if (lastClip.clip == null) {
            mus = lastClip;
            mus.clip = aClip;
        } else {
            mus = new MusicSetting() {
                volume = 1f,
                pitch = 1f,
                isExpanded = true,
                audLocation = pList.bulkLocationMode
            };

            switch (pList.bulkLocationMode) {
                case MasterAudio.AudioLocation.Clip:
                    mus.clip = aClip;
                    mus.songName = aClip.name;
                    break;
                case MasterAudio.AudioLocation.ResourceFile:
                    var resourceFileName = DTGUIHelper.GetResourcePath(aClip);
                    if (string.IsNullOrEmpty(resourceFileName)) {
                        resourceFileName = aClip.name;
                    }

                    mus.resourceFileName = resourceFileName;
                    mus.songName = aClip.name;
                    break;
            }

            pList.MusicSettings.Add(mus);
        }
    }
    public override void OnInspectorGUI()
    {
        EditorGUIUtility.LookLikeControls();
        EditorGUI.indentLevel = 0;

        sounds = (MasterAudio)target;

        if (MasterAudioInspectorResources.logoTexture != null) {
            DTGUIHelper.ShowHeaderTexture(MasterAudioInspectorResources.logoTexture);
        }

        this.ScanGroups();

        if (!isValid) {
            return;
        }

        var isInProjectView = DTGUIHelper.IsPrefabInProjectView(sounds);

        playlistNames = new List<string>();
        MasterAudio.Playlist pList = null;

        var maxPlaylistNameChars = 11;
        for (var i = 0; i < sounds.musicPlaylists.Count; i++) {
            pList = sounds.musicPlaylists[i];

            playlistNames.Add(pList.playlistName);
            if (pList.playlistName.Length > maxPlaylistNameChars) {
                maxPlaylistNameChars = pList.playlistName.Length;
            }
        }

        var groupNameList = GroupNameList;

        var busFilterList = new List<string>();
        busFilterList.Add(MasterAudio.ALL_BUSES_NAME);
        busFilterList.Add(MasterAudioGroup.NO_BUS);

        var maxChars = 9;
        var busList = new List<string>();
        busList.Add(MasterAudioGroup.NO_BUS);
        busList.Add(NEW_BUS_NAME);

        var busVoiceLimitList = new List<string>();
        busVoiceLimitList.Add(MasterAudio.NO_VOICE_LIMIT_NAME);

        for (var i = 1; i <= 32; i++) {
            busVoiceLimitList.Add(i.ToString());
        }

        GroupBus bus = null;
        for (var i = 0; i < sounds.groupBuses.Count; i++) {
            bus = sounds.groupBuses[i];
            busList.Add(bus.busName);
            busFilterList.Add(bus.busName);

            if (bus.busName.Length > maxChars) {
                maxChars = bus.busName.Length;
            }
        }
        var busListWidth = 9 * maxChars;
        var playlistListWidth = 9 * maxPlaylistNameChars;

        PlaylistController.Instances = null;
        var pcs = PlaylistController.Instances;
        var plControllerInScene = pcs.Count > 0;

        // mixer master volume!
        EditorGUILayout.BeginHorizontal();
        var volumeBefore = sounds.masterAudioVolume;
        GUILayout.Label("Master Mixer Volume");
        GUILayout.Space(23);

        var newMasterVol = EditorGUILayout.Slider(sounds.masterAudioVolume, 0f, 1f, GUILayout.Width(252));
        if (newMasterVol != sounds.masterAudioVolume) {
            UndoHelper.RecordObjectPropertyForUndo(sounds, "change Master Mixer Volume");
            if (Application.isPlaying) {
                MasterAudio.MasterVolumeLevel = newMasterVol;
            } else {
                sounds.masterAudioVolume = newMasterVol;
            }
        }
        GUILayout.Space(10);

        var mixerMuteButtonPressed = DTGUIHelper.AddMixerMuteButton("Mixer", sounds);

        GUILayout.FlexibleSpace();

        if (mixerMuteButtonPressed == DTGUIHelper.DTFunctionButtons.Mute) {
            UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Mixer Mute");

            sounds.mixerMuted = !sounds.mixerMuted;
            if (Application.isPlaying) {
                MasterAudio.MixerMuted = sounds.mixerMuted;
            } else {
                for (var i = 0; i < groups.Count; i++) {
                    var aGroup = groups[i];
                    aGroup.isMuted = sounds.mixerMuted;
                    if (aGroup.isMuted) {
                        aGroup.isSoloed = false;
                    }
                }
            }
        }

        EditorGUILayout.EndHorizontal();

        if (volumeBefore != sounds.masterAudioVolume) {
            // fix it for realtime adjustments!
            MasterAudio.MasterVolumeLevel = sounds.masterAudioVolume;
        }

        // playlist master volume!
        if (plControllerInScene) {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Master Playlist Volume");
            GUILayout.Space(14);
            var newPlaylistVol = EditorGUILayout.Slider(sounds.masterPlaylistVolume, 0f, 1f, GUILayout.Width(252));
            if (newPlaylistVol != sounds.masterPlaylistVolume) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Master Playlist Volume");
                if (Application.isPlaying) {
                    MasterAudio.PlaylistMasterVolume = newPlaylistVol;
                } else {
                    sounds.masterPlaylistVolume = newPlaylistVol;
                }
            }
            GUILayout.Space(10);
            var playlistMuteButtonPressed = DTGUIHelper.AddPlaylistMuteButton("All Playlists", sounds);
            if (playlistMuteButtonPressed == DTGUIHelper.DTFunctionButtons.Mute) {
                if (Application.isPlaying) {
                    MasterAudio.PlaylistsMuted = !MasterAudio.PlaylistsMuted;
                } else {
                    sounds.playlistsMuted = !sounds.playlistsMuted;

                    for (var i = 0; i < pcs.Count; i++) {
                        if (sounds.playlistsMuted) {
                            pcs[i].MutePlaylist();
                        } else {
                            pcs[i].UnmutePlaylist();
                        }
                    }
                }
            }

            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Master Crossfade Time");
            GUILayout.Space(11);
            var newCrossTime = EditorGUILayout.Slider(sounds.crossFadeTime, 0f, 10f, GUILayout.Width(252));
            if (newCrossTime != sounds.crossFadeTime) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Master Crossfade Time");
                sounds.crossFadeTime = newCrossTime;
            }
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            // jukebox controls
            if (Application.isPlaying) {
                DisplayJukebox();
            }
        }

        // Music Ducking Start
        EditorGUI.indentLevel = 0;
        GUI.color = sounds.showAdvancedSettings ? activeClr : inactiveClr;
        EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);

        var newAdv = EditorGUILayout.Toggle("Show Advanced", sounds.showAdvancedSettings);
        if (newAdv != sounds.showAdvancedSettings) {
            UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Show Advanced");
            sounds.showAdvancedSettings = newAdv;
        }
        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        if (sounds.showAdvancedSettings) {
            if (!Application.isPlaying) {
                var newPersist = EditorGUILayout.Toggle("Persist Across Scenes", sounds.persistBetweenScenes);
                if (newPersist != sounds.persistBetweenScenes) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Persist Across Scenes");
                    sounds.persistBetweenScenes = newPersist;
                }
            }

            if (sounds.persistBetweenScenes && plControllerInScene) {
                DTGUIHelper.ShowColorWarning("*Playlist Controller will also persist between scenes!");
            }

            var newAutoPrioritize = EditorGUILayout.Toggle("Apply Distance Priority", sounds.prioritizeOnDistance);
            if (newAutoPrioritize != sounds.prioritizeOnDistance) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Prioritize By Distance");
                sounds.prioritizeOnDistance = newAutoPrioritize;
            }

            if (sounds.prioritizeOnDistance) {
                EditorGUI.indentLevel = 1;

                var reevalIndex = sounds.rePrioritizeEverySecIndex;

                var evalTimes = new List<string>();
                for (var i = 0; i < reevaluatePriorityTimes.Count; i++) {
                    evalTimes.Add(reevaluatePriorityTimes[i].ToString() + " seconds");
                }

                var newRepri = EditorGUILayout.Popup("Reprioritize Time Gap", reevalIndex, evalTimes.ToArray());
                if (newRepri != reevalIndex) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "change Re-evaluate time");
                    sounds.rePrioritizeEverySecIndex = newRepri;
                }

                var newContinual = EditorGUILayout.Toggle("Use Clip Age Priority", sounds.useClipAgePriority);
                if (newContinual != sounds.useClipAgePriority) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Use Clip Age Priority");
                    sounds.useClipAgePriority = newContinual;
                }
            }

            EditorGUI.indentLevel = 0;
            var newFast = EditorGUILayout.Toggle("Fast GUI Refresh", sounds.enableFastResponse);
            if (newFast != sounds.enableFastResponse) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Fast GUI Refresh");
                sounds.enableFastResponse = newFast;
            }

            var newGiz = EditorGUILayout.Toggle("Show Variation Gizmos", sounds.showGizmos);
            if (newGiz != sounds.showGizmos) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Show Variation Gizmos");
                sounds.showGizmos = newGiz;
            }

            var newResourcePause = EditorGUILayout.Toggle("Keep Paused Resources", sounds.resourceClipsPauseDoNotUnload);
            if (newResourcePause != sounds.resourceClipsPauseDoNotUnload) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Keep Paused Resources");
                sounds.resourceClipsPauseDoNotUnload = newResourcePause;
            }

            var newLog = EditorGUILayout.Toggle("Disable Logging", sounds.disableLogging);
            if (newLog != sounds.disableLogging) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Disable Logging");
                sounds.disableLogging = newLog;
            }

            if (!sounds.disableLogging) {
                newLog = EditorGUILayout.Toggle("Log All Sounds", sounds.LogSounds);
                if (newLog != sounds.LogSounds) {
                    if (Application.isPlaying) {
                        MasterAudio.LogSoundsEnabled = sounds.LogSounds;
                    }
                    sounds.LogSounds = newLog;
                }
            } else {
                DTGUIHelper.ShowLargeBarAlert("Logging is disabled.");
            }
        }

        // Music Ducking Start
        EditorGUI.indentLevel = 0;
        GUI.color = sounds.showMusicDucking ? activeClr : inactiveClr;
        EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);

        var newShowDuck = EditorGUILayout.Toggle("Show Music Ducking", sounds.showMusicDucking);
        if (newShowDuck != sounds.showMusicDucking) {
            UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Show Music Ducking");
            sounds.showMusicDucking = newShowDuck;
        }
        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        if (sounds.showMusicDucking) {
            var newEnableDuck = EditorGUILayout.BeginToggleGroup("Enable Ducking", sounds.EnableMusicDucking);
            if (newEnableDuck != sounds.EnableMusicDucking) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Enable Ducking");
                sounds.EnableMusicDucking = newEnableDuck;
            }

            EditorGUILayout.Separator();

            var newMult = EditorGUILayout.Slider("Ducked Vol Multiplier", sounds.duckedVolumeMultiplier, 0f, 1f);
            if (newMult != sounds.duckedVolumeMultiplier) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Ducked Vol Multiplier");
                sounds.DuckedVolumeMultiplier = newMult;
            }

            var newDefault = EditorGUILayout.Slider("Default Begin Unduck", sounds.defaultRiseVolStart, 0f, 1f);
            if (newDefault != sounds.defaultRiseVolStart) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Default Begin Unduck");
                sounds.defaultRiseVolStart = newDefault;
            }

            GUI.contentColor = Color.green;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(10);

            if (GUILayout.Button(new GUIContent("Add Duck Group"), EditorStyles.toolbarButton, GUILayout.Width(100))) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "Add Duck Group");
                sounds.musicDuckingSounds.Add(new DuckGroupInfo() {
                    soundType = MasterAudio.NO_GROUP_NAME,
                    riseVolStart = sounds.defaultRiseVolStart
                });
            }

            EditorGUILayout.EndHorizontal();
            GUI.contentColor = Color.white;
            EditorGUILayout.Separator();

            if (sounds.musicDuckingSounds.Count == 0) {
                DTGUIHelper.ShowColorWarning("*You currently have no ducking sounds set up.");
            } else {
                int? duckSoundToRemove = null;

                for (var i = 0; i < sounds.musicDuckingSounds.Count; i++) {
                    var duckSound = sounds.musicDuckingSounds[i];
                    var index = groupNameList.IndexOf(duckSound.soundType);
                    if (index == -1) {
                        index = 0;
                    }

                    EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
                    var newIndex = EditorGUILayout.Popup(index, groupNameList.ToArray(), GUILayout.MaxWidth(200));
                    if (newIndex >= 0) {
                        if (index != newIndex) {
                            UndoHelper.RecordObjectPropertyForUndo(sounds, "change Duck Group");
                        }
                        duckSound.soundType = groupNameList[newIndex];
                    }

                    GUI.contentColor = Color.green;
                    GUILayout.TextField("Begin Unduck " + duckSound.riseVolStart.ToString("N2"), 20, EditorStyles.miniLabel);

                    var newUnduck = GUILayout.HorizontalSlider(duckSound.riseVolStart, 0f, 1f, GUILayout.Width(60));
                    if (newUnduck != duckSound.riseVolStart) {
                        UndoHelper.RecordObjectPropertyForUndo(sounds, "change Begin Unduck");
                        duckSound.riseVolStart = newUnduck;
                    }
                    GUI.contentColor = Color.white;

                    GUILayout.FlexibleSpace();
                    GUILayout.Space(10);
                    if (DTGUIHelper.AddDeleteIcon("Duck Sound")) {
                        duckSoundToRemove = i;
                    }

                    EditorGUILayout.EndHorizontal();
                }

                if (duckSoundToRemove.HasValue) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "delete Duck Group");
                    sounds.musicDuckingSounds.RemoveAt(duckSoundToRemove.Value);
                }

            }
            EditorGUILayout.EndToggleGroup();

            EditorGUILayout.Separator();
        }
        // Music Ducking End

        // Sound Groups Start
        EditorGUILayout.BeginHorizontal();
        EditorGUI.indentLevel = 0;  // Space will handle this for the header

        GUI.color = sounds.areGroupsExpanded ? activeClr : inactiveClr;
        EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
        var newGroupEx = EditorGUILayout.Toggle("Show Group Mixer", sounds.areGroupsExpanded);
        if (newGroupEx != sounds.areGroupsExpanded) {
            UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Show Group Mixer");
            sounds.areGroupsExpanded = newGroupEx;
        }

        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;
        EditorGUILayout.EndHorizontal();

        GameObject groupToDelete = null;

        if (sounds.areGroupsExpanded) {
            EditorGUI.indentLevel = 0;

            var newGroupMode = (MasterAudio.DragGroupMode) EditorGUILayout.EnumPopup("Bulk Creation Mode", sounds.curDragGroupMode);
            if (newGroupMode != sounds.curDragGroupMode) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Bulk Creation Mode");
                sounds.curDragGroupMode = newGroupMode;
            }

            var newBulkMode = (MasterAudio.AudioLocation) EditorGUILayout.EnumPopup("Variation Create Mode",  sounds.bulkLocationMode);
            if (newBulkMode != sounds.bulkLocationMode) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Bulk Variation Mode");
                sounds.bulkLocationMode = newBulkMode;
            }

            if (sounds.bulkLocationMode == MasterAudio.AudioLocation.ResourceFile) {
                DTGUIHelper.ShowColorWarning("*Resource mode: make sure to drag from Resource folders only.");
            }

            // create groups start
            EditorGUILayout.BeginVertical();
            var anEvent = Event.current;

            GUI.color = Color.yellow;

            if (isInProjectView) {
                DTGUIHelper.ShowLargeBarAlert("*You are in Project View and cannot create or navigate Groups.");
                DTGUIHelper.ShowLargeBarAlert("*Pull this prefab into the Scene to create Groups.");
            } else {
                var dragArea = GUILayoutUtility.GetRect(0f,35f,GUILayout.ExpandWidth(true));
                GUI.Box (dragArea, "Drag Audio clips here to create groups!");

                GUI.color = Color.white;

                switch (anEvent.type) {
                    case EventType.DragUpdated:
                    case EventType.DragPerform:
                        if(!dragArea.Contains(anEvent.mousePosition)) {
                            break;
                        }

                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                        if(anEvent.type == EventType.DragPerform) {
                            DragAndDrop.AcceptDrag();

                            Transform groupTrans = null;

                            foreach (var dragged in DragAndDrop.objectReferences) {
                                var aClip = dragged as AudioClip;
                                if(aClip == null) {
                                    continue;
                                }

                                if (sounds.curDragGroupMode == MasterAudio.DragGroupMode.OneGroupPerClip) {
                                    CreateSoundGroup(aClip);
                                } else {
                                    if (groupTrans == null) { // one group with variations
                                        groupTrans = CreateSoundGroup(aClip);
                                    } else {
                                        CreateVariation(groupTrans, aClip);
                                        // create the variations
                                    }
                                }
                            }
                        }
                        Event.current.Use();
                        break;
                }
            }
            EditorGUILayout.EndVertical();
            // create groups end

            EditorGUILayout.LabelField("Group Control", EditorStyles.miniBoldLabel);

            if (sounds.groupBuses.Count > 0) {
                var newGroupByBus = GUILayout.Toggle(sounds.groupByBus, "Group by Bus");
                if (newGroupByBus != sounds.groupByBus) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Group by Bus");
                    sounds.groupByBus = newGroupByBus;
                }
            }

            var newBusFilterIndex = -1;
            var busFilterActive = false;

            if (sounds.groupBuses.Count > 0) {
                busFilterActive = true;
                var oldBusFilter = busFilterList.IndexOf(sounds.busFilter);
                if (oldBusFilter == -1) {
                     oldBusFilter = 0;
                }

                newBusFilterIndex = EditorGUILayout.Popup("Bus Filter", oldBusFilter, busFilterList.ToArray());

                var newBusFilter = busFilterList[newBusFilterIndex];

                if (sounds.busFilter != newBusFilter) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "change Bus Filter");
                    sounds.busFilter = newBusFilter;
                }
            }

            var newUseTextGroupFilter = EditorGUILayout.Toggle("Use Text Group Filter", sounds.useTextGroupFilter);
            if (newUseTextGroupFilter != sounds.useTextGroupFilter) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Use Text Group Filter");
                sounds.useTextGroupFilter = newUseTextGroupFilter;
            }

            if (sounds.useTextGroupFilter) {
                EditorGUI.indentLevel = 1;

                EditorGUILayout.BeginHorizontal();
                GUILayout.Space(10);
                GUILayout.Label("Text Group Filter", GUILayout.Width(140));
                var newTextFilter = GUILayout.TextField(sounds.textGroupFilter, GUILayout.Width(180));
                if (newTextFilter != sounds.textGroupFilter) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "change Text Group Filter");
                    sounds.textGroupFilter = newTextFilter;
                }
                GUILayout.Space(10);
                GUI.contentColor = Color.green;
                if (GUILayout.Button("Clear", EditorStyles.toolbarButton, GUILayout.Width(70))) {
                    sounds.textGroupFilter = string.Empty;
                }
                GUI.contentColor = Color.white;
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.Separator();
            }

            EditorGUI.indentLevel = 0;
            DTGUIHelper.DTFunctionButtons groupButtonPressed = DTGUIHelper.DTFunctionButtons.None;

            MasterAudioGroup aGroup = null;
            var filteredGroups = new List<MasterAudioGroup>();

            filteredGroups.AddRange(this.groups);

            if (busFilterActive && !string.IsNullOrEmpty(sounds.busFilter)) {
                if (newBusFilterIndex == 0) {
                    // no filter
                } else if (newBusFilterIndex == 1) {
                    filteredGroups.RemoveAll(delegate(MasterAudioGroup obj) {
                        return obj.busIndex != 0;
                    });
                } else {
                    filteredGroups.RemoveAll(delegate(MasterAudioGroup obj) {
                        return obj.busIndex != newBusFilterIndex;
                    });
                }
            }

            if (sounds.useTextGroupFilter) {
                if (!string.IsNullOrEmpty(sounds.textGroupFilter)) {
                    filteredGroups.RemoveAll(delegate(MasterAudioGroup obj) {
                        return !obj.transform.name.ToLower().Contains(sounds.textGroupFilter.ToLower());
                    });
                }
            }

            var totalVoiceCount = 0;

            if (groups.Count == 0) {
                DTGUIHelper.ShowColorWarning("*You currently have zero Sound Groups.");
            } else {
                var groupsFiltered = this.groups.Count - filteredGroups.Count;
                if (groupsFiltered > 0) {
                    DTGUIHelper.ShowLargeBarAlert(string.Format("{0} Group(s) filtered out.", groupsFiltered));
                }

                int? busToCreate = null;

                for (var l = 0; l < filteredGroups.Count; l++) {
                    EditorGUI.indentLevel = 0;
                    aGroup = filteredGroups[l];

                    string sType = string.Empty;
                    if (Application.isPlaying) {
                        sType = aGroup.name;
                    }

                    EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
                    var groupName = aGroup.name;

                    if (Application.isPlaying) {
                        var groupVoices = aGroup.ActiveVoices;

                        GUI.color = Color.yellow;
                        if (aGroup.limitPolyphony && aGroup.voiceLimitCount == groupVoices) {
                            GUI.contentColor = Color.red;
                        }
                        GUILayout.Label(string.Format("[{0}]", groupVoices));
                        GUI.color = Color.white;
                        GUI.contentColor = Color.white;

                        totalVoiceCount += groupVoices;
                    }

                    EditorGUILayout.LabelField(groupName, EditorStyles.label, GUILayout.MinWidth(50));
                    //GUILayout.Space(90);

                    GUILayout.FlexibleSpace();
                    EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(50));

                    // find bus.
                    var selectedBusIndex = aGroup.busIndex == -1 ? 0 : aGroup.busIndex;

                    GUI.contentColor = Color.white;
                    GUI.color = Color.cyan;

                    var busIndex = EditorGUILayout.Popup("", selectedBusIndex, busList.ToArray(), GUILayout.Width(busListWidth));
                    if (busIndex == -1) {
                        busIndex = 0;
                    }

                    if (aGroup.busIndex != busIndex && busIndex != 1) {
                        UndoHelper.RecordObjectPropertyForUndo(aGroup, "change Group Bus");
                    }

                    if (busIndex != 1) { // don't change the index, so undo will work.
                        aGroup.busIndex = busIndex;
                    }

                    GUI.color = Color.white;

                    if (selectedBusIndex != busIndex) {
                        if (busIndex == 1) {
                            busToCreate = l;
                        } else if (busIndex >= MasterAudio.HARD_CODED_BUS_OPTIONS) {
                            GroupBus newBus = sounds.groupBuses[busIndex - MasterAudio.HARD_CODED_BUS_OPTIONS];
                            if (Application.isPlaying) {
                                var statGroup = MasterAudio.GrabGroup(sType);
                                statGroup.busIndex = busIndex;

                                if (newBus.isMuted) {
                                    MasterAudio.MuteGroup(aGroup.name);
                                } else if (newBus.isSoloed) {
                                    MasterAudio.SoloGroup(aGroup.name);
                                }
                            } else {
                                // check if bus soloed or muted.
                                if (newBus.isMuted) {
                                    aGroup.isMuted = true;
                                    aGroup.isSoloed = false;
                                } else if (newBus.isSoloed) {
                                    aGroup.isMuted = false;
                                    aGroup.isSoloed = true;
                                }
                            }
                        }
                    }

                    GUI.contentColor = Color.green;
                    GUILayout.TextField("V " + aGroup.groupMasterVolume.ToString("N2"), 6, EditorStyles.miniLabel);

                    var newVol = GUILayout.HorizontalSlider(aGroup.groupMasterVolume, 0f, 1f, GUILayout.Width(60));
                    if (newVol != aGroup.groupMasterVolume) {
                        UndoHelper.RecordObjectPropertyForUndo(aGroup, "change Group Volume");
                        aGroup.groupMasterVolume = newVol;
                        if (Application.isPlaying) {
                            MasterAudio.SetGroupVolume(aGroup.name, aGroup.groupMasterVolume);
                        }
                    }

                    GUI.contentColor = Color.white;
                    DTGUIHelper.AddLedSignalLight(sounds, groupName);

                    groupButtonPressed = DTGUIHelper.AddMixerButtons(aGroup, "Group");

                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.EndHorizontal();

                    GroupBus groupBus = null;
                    var groupBusIndex = aGroup.busIndex - MasterAudio.HARD_CODED_BUS_OPTIONS;
                    if (groupBusIndex >= 0 && groupBusIndex < sounds.groupBuses.Count) {
                        groupBus = sounds.groupBuses[groupBusIndex];
                    }

                    switch (groupButtonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Play:
                            if (Application.isPlaying) {
                                MasterAudio.PlaySound(aGroup.name);
                            } else {
                                var rndIndex = UnityEngine.Random.Range(0, aGroup.groupVariations.Count);
                                var rndVar = aGroup.groupVariations[rndIndex];

                                if (rndVar.audLocation == MasterAudio.AudioLocation.ResourceFile) {
                                    MasterAudio.PreviewerInstance.Stop();
                                    MasterAudio.PreviewerInstance.PlayOneShot(Resources.Load(rndVar.resourceFileName) as AudioClip, rndVar.audio.volume);
                                } else {
                                    rndVar.audio.Play();
                                }
                            }
                            break;
                        case DTGUIHelper.DTFunctionButtons.Stop:
                            if (Application.isPlaying) {
                                MasterAudio.StopAllOfSound(aGroup.name);
                            } else {
                                var hasResourceFile = false;
                                for (var i = 0; i < aGroup.groupVariations.Count; i++) {
                                    aGroup.groupVariations[i].audio.Stop();
                                    if (aGroup.groupVariations[i].audLocation == MasterAudio.AudioLocation.ResourceFile) {
                                        hasResourceFile = true;
                                    }
                                }

                                if (hasResourceFile) {
                                    MasterAudio.PreviewerInstance.Stop();
                                }
                            }
                            break;
                        case DTGUIHelper.DTFunctionButtons.Mute:
                            if (groupBus != null && (groupBus.isMuted || groupBus.isSoloed)) {
                                if (Application.isPlaying) {
                                    Debug.LogWarning(NO_MUTE_SOLO_ALLOWED);
                                } else {
                                    DTGUIHelper.ShowAlert(NO_MUTE_SOLO_ALLOWED);
                                }
                            } else {
                                UndoHelper.RecordObjectPropertyForUndo(aGroup, "toggle Group mute");

                                if (Application.isPlaying) {
                                    if (aGroup.isMuted) {
                                        MasterAudio.UnmuteGroup(sType);
                                    } else {
                                        MasterAudio.MuteGroup(sType);
                                    }
                                } else {
                                    aGroup.isMuted = !aGroup.isMuted;
                                    if (aGroup.isMuted) {
                                        aGroup.isSoloed = false;
                                    }
                                }
                            }
                            break;
                        case DTGUIHelper.DTFunctionButtons.Solo:
                            if (groupBus != null && (groupBus.isMuted || groupBus.isSoloed)) {
                                if (Application.isPlaying) {
                                    Debug.LogWarning(NO_MUTE_SOLO_ALLOWED);
                                } else {
                                    DTGUIHelper.ShowAlert(NO_MUTE_SOLO_ALLOWED);
                                }
                            } else {
                                UndoHelper.RecordObjectPropertyForUndo(aGroup, "toggle Group solo");

                                if (Application.isPlaying) {
                                    if (aGroup.isSoloed) {
                                        MasterAudio.UnsoloGroup(sType);
                                    } else {
                                        MasterAudio.SoloGroup(sType);
                                    }
                                } else {
                                    aGroup.isSoloed = !aGroup.isSoloed;
                                    if (aGroup.isSoloed) {
                                        aGroup.isMuted = false;
                                    }
                                }
                            }
                            break;
                        case DTGUIHelper.DTFunctionButtons.Go:
                            Selection.activeObject = aGroup.transform;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            groupToDelete = aGroup.transform.gameObject;
                            break;
                    }

                    EditorUtility.SetDirty(aGroup);
                }

                if (busToCreate.HasValue) {
                    CreateBus(busToCreate.Value);
                }

                if (groupToDelete != null) {
                    sounds.musicDuckingSounds.RemoveAll(delegate(DuckGroupInfo obj) {
                        return obj.soundType == groupToDelete.name;
                    });
                    UndoHelper.DestroyForUndo(groupToDelete);
                }

                if (Application.isPlaying) {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(6);
                    GUI.color = Color.yellow;
                    EditorGUILayout.LabelField(string.Format("[{0}] Total Active Voices", totalVoiceCount));
                    GUI.color = Color.white;
                    EditorGUILayout.EndHorizontal();
                }

                EditorGUILayout.Separator();
                EditorGUILayout.BeginHorizontal();
                GUILayout.Space(10);
                GUI.contentColor = Color.green;
                if (GUILayout.Button(new GUIContent("Mute/Solo Reset", "Turn off all group mute and solo switches"), EditorStyles.toolbarButton, GUILayout.Width(120))) {
                    UndoHelper.RecordObjectsForUndo(this.groups.ToArray(), "Mute/Solo Reset");

                    for (var l = 0; l < this.groups.Count; l++) {
                        aGroup = this.groups[l];
                        aGroup.isSoloed = false;
                        aGroup.isMuted = false;
                    }

                }

                GUILayout.Space(6);

                if (GUILayout.Button(new GUIContent("Max Group Volumes", "Reset all group volumes to full"), EditorStyles.toolbarButton, GUILayout.Width(120))) {
                    UndoHelper.RecordObjectsForUndo(this.groups.ToArray(), "Max Group Volumes");

                    for (var l = 0; l < this.groups.Count; l++) {
                        aGroup = this.groups[l];
                        aGroup.groupMasterVolume = 1f;
                    }
                }

                GUI.contentColor = Color.white;

                EditorGUILayout.EndHorizontal();
            }
            // Sound Groups End

            // Buses
            if (sounds.groupBuses.Count > 0) {
                EditorGUILayout.Separator();
                EditorGUILayout.LabelField("Bus Control", EditorStyles.miniBoldLabel);

                GroupBus aBus = null;
                DTGUIHelper.DTFunctionButtons busButtonPressed = DTGUIHelper.DTFunctionButtons.None;
                int? busToDelete = null;
                int? busToSolo = null;
                int? busToMute = null;

                for (var i = 0; i < sounds.groupBuses.Count; i++) {
                    aBus = sounds.groupBuses[i];

                    EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);

                    if (Application.isPlaying) {
                        GUI.color = Color.yellow;
                        if (aBus.BusVoiceLimitReached) {
                            GUI.contentColor = Color.red;
                        }
                        GUILayout.Label(string.Format("[{0:D2}]", aBus.ActiveVoices));
                        GUI.color = Color.white;
                        GUI.contentColor = Color.white;
                    }

                    var newBusName = EditorGUILayout.TextField("", aBus.busName, GUILayout.MaxWidth(200));
                    if (newBusName != aBus.busName) {
                        UndoHelper.RecordObjectPropertyForUndo(sounds, "change Bus Name");
                        aBus.busName = newBusName;
                    }

                    GUILayout.FlexibleSpace();

                    GUILayout.Label("Voices");
                    GUI.color = Color.cyan;

                    var oldLimitIndex = busVoiceLimitList.IndexOf(aBus.voiceLimit.ToString());
                    if (oldLimitIndex == -1) {
                        oldLimitIndex = 0;
                    }
                    var busVoiceLimitIndex = EditorGUILayout.Popup("", oldLimitIndex, busVoiceLimitList.ToArray(), GUILayout.MaxWidth(70));
                    if (busVoiceLimitIndex != oldLimitIndex) {
                        UndoHelper.RecordObjectPropertyForUndo(sounds, "change Bus Voice Limit");
                        aBus.voiceLimit = busVoiceLimitIndex <= 0 ? -1 : busVoiceLimitIndex;
                    }

                    GUI.color = Color.white;

                    EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(50));
                    GUILayout.TextField("V " + aBus.volume.ToString("N2"), 6, EditorStyles.miniLabel);

                    var newBusVol = GUILayout.HorizontalSlider(aBus.volume, 0f, 1f, GUILayout.Width(86));
                    if (newBusVol != aBus.volume) {
                        UndoHelper.RecordObjectPropertyForUndo(sounds, "change Bus Volume");
                        aBus.volume = newBusVol;
                        if (Application.isPlaying) {
                            MasterAudio.SetBusVolumeByName(aBus.busName, aBus.volume);
                        }
                    }

                    GUI.contentColor = Color.white;

                    busButtonPressed = DTGUIHelper.AddMixerBusButtons(aBus);

                    switch (busButtonPressed) {
                    case DTGUIHelper.DTFunctionButtons.Remove:
                        busToDelete = i;
                        break;
                    case DTGUIHelper.DTFunctionButtons.Solo:
                        busToSolo = i;
                        break;
                    case DTGUIHelper.DTFunctionButtons.Mute:
                        busToMute = i;
                        break;
                    }

                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.EndHorizontal();
                }

                if (busToDelete.HasValue) {
                    DeleteBus(busToDelete.Value);
                }
                if (busToMute.HasValue) {
                    MuteBus(busToMute.Value);
                }
                if (busToSolo.HasValue) {
                    SoloBus(busToSolo.Value);
                }

                if (Application.isPlaying) {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(6);
                    GUI.color = Color.yellow;
                    EditorGUILayout.LabelField(string.Format("[{0:D2}] Total Active Voices", totalVoiceCount));
                    GUI.color = Color.white;
                    EditorGUILayout.EndHorizontal();
                }

                EditorGUILayout.Separator();
                EditorGUILayout.BeginHorizontal();
                GUILayout.Space(10);
                GUI.contentColor = Color.green;

                if (GUILayout.Button(new GUIContent("Mute/Solo Reset", "Turn off all bus mute and solo switches"), EditorStyles.toolbarButton, GUILayout.Width(120))) {
                    BusMuteSoloReset();
                }

                GUILayout.Space(6);

                if (GUILayout.Button(new GUIContent("Max Bus Volumes", "Reset all bus volumes to full"), EditorStyles.toolbarButton, GUILayout.Width(120))) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "Max Bus Volumes");

                    for (var l = 0; l < sounds.groupBuses.Count; l++) {
                        aBus = sounds.groupBuses[l];
                        aBus.volume = 1f;
                    }
                }

                GUI.contentColor = Color.white;

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.Separator();
        }
        // Sound Buses End

        // Music playlist Start
        EditorGUILayout.BeginHorizontal();
        EditorGUI.indentLevel = 0;  // Space will handle this for the header

        GUI.color = sounds.playListExpanded ? activeClr : inactiveClr;
        EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
        var isExp = EditorGUILayout.Toggle("Show Playlist Settings", sounds.playListExpanded);
        if (isExp != sounds.playListExpanded) {
            UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Show Playlist Settings");
            sounds.playListExpanded = isExp;
        }

        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        EditorGUILayout.EndHorizontal();

        if (sounds.playListExpanded) {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Playlist Controller Setup", EditorStyles.miniBoldLabel, GUILayout.Width(146));
            if (plControllerInScene) {
                GUILayout.FlexibleSpace();
                EditorGUILayout.LabelField("Sync Grp.", EditorStyles.miniBoldLabel, GUILayout.Width(54));
                EditorGUILayout.LabelField("Initial Playlist", EditorStyles.miniBoldLabel, GUILayout.Width(100));
                GUILayout.Space(204);
            }
            EditorGUILayout.EndHorizontal();

            if (!plControllerInScene) {
                DTGUIHelper.ShowColorWarning("There are no Playlist Controllers in the scene. Music will not play.");
            } else {
                int? indexToDelete = null;

                playlistNames.Insert(0, MasterAudio.NO_PLAYLIST_NAME);

                var syncGroupList = new List<string>();
                for (var i = 0; i < 4; i++) {
                    syncGroupList.Add((i + 1).ToString());
                }
                syncGroupList.Insert(0, MasterAudio.NO_GROUP_NAME);

                for (var i = 0; i < pcs.Count; i++) {
                    var control = pcs[i];
                    EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
                    GUILayout.Label(control.name);

                    GUILayout.FlexibleSpace();

                    GUI.color = Color.cyan;
                    var syncIndex = syncGroupList.IndexOf(control.syncGroupNum.ToString());
                    if (syncIndex == -1) {
                        syncIndex = 0;
                    }
                    var newSync = EditorGUILayout.Popup("", syncIndex, syncGroupList.ToArray(), GUILayout.Width(55));
                    if (newSync != syncIndex) {
                        UndoHelper.RecordObjectPropertyForUndo(control, "change Controller Sync Group");
                        control.syncGroupNum = newSync;
                    }

                    var origIndex = playlistNames.IndexOf(control.startPlaylistName);
                    if (origIndex == -1) {
                        origIndex = 0;
                    }
                    var newIndex = EditorGUILayout.Popup("", origIndex, playlistNames.ToArray(), GUILayout.Width(playlistListWidth));
                    if (newIndex != origIndex) {
                        UndoHelper.RecordObjectPropertyForUndo(control, "change Playlist Controller initial Playlist");
                        control.startPlaylistName = playlistNames[newIndex];
                    }
                    GUI.color = Color.white;

                    GUI.contentColor = Color.green;
                    GUILayout.TextField("V " + control.playlistVolume.ToString("N2"), 6, EditorStyles.miniLabel);
                    var newVol = GUILayout.HorizontalSlider(control.playlistVolume, 0f, 1f, GUILayout.Width(74));

                    if (newVol != control.playlistVolume) {
                        UndoHelper.RecordObjectPropertyForUndo(control, "change Playlist Controller volume");
                        control.playlistVolume = newVol;
                        control.UpdateMasterVolume();
                    }

                    GUI.contentColor = Color.white;

                    var buttonPressed = DTGUIHelper.AddPlaylistControllerSetupButtons(control, "Playlist Controller", false);

                    EditorGUILayout.EndHorizontal();

                    switch (buttonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Go:
                            Selection.activeObject = control.transform;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            indexToDelete = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Mute:
                            control.ToggleMutePlaylist();
                            break;
                    }

                    EditorUtility.SetDirty(control);
                }

                if (indexToDelete.HasValue) {
                    UndoHelper.DestroyForUndo(pcs[indexToDelete.Value].gameObject);
                }
            }

            EditorGUILayout.Separator();
            GUI.contentColor = Color.green;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(10);
            if (GUILayout.Button(new GUIContent("Create Playlist Controller"), EditorStyles.toolbarButton, GUILayout.Width(150))) {
                var go = GameObject.Instantiate(sounds.playlistControllerPrefab.gameObject);
                go.name = "PlaylistController";

                UndoHelper.CreateObjectForUndo(go as GameObject, "create Playlist Controller");
            }
            EditorGUILayout.EndHorizontal();
            GUI.contentColor = Color.white;
            EditorGUILayout.Separator();

            EditorGUILayout.LabelField("Playlist Setup", EditorStyles.miniBoldLabel);
            EditorGUI.indentLevel = 0;  // Space will handle this for the header

            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            var oldPlayExpanded = DTGUIHelper.Foldout(sounds.playlistEditorExpanded, "Playlists");
            if (oldPlayExpanded != sounds.playlistEditorExpanded) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Playlists");
                sounds.playlistEditorExpanded = oldPlayExpanded;
            }

            EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(100));

            if (sounds.musicPlaylists.Count > 0) {
                GUIContent content;
                var collapseIcon = '\u2261'.ToString();
                content = new GUIContent(collapseIcon, "Click to collapse all");
                var masterCollapse = GUILayout.Button(content, EditorStyles.toolbarButton);

                var expandIcon = '\u25A1'.ToString();
                content = new GUIContent(expandIcon, "Click to expand all");
                var masterExpand = GUILayout.Button(content, EditorStyles.toolbarButton);
                if (masterExpand) {
                    ExpandCollapseAllPlaylists(true);
                }
                if (masterCollapse) {
                    ExpandCollapseAllPlaylists(false);
                }
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.EndHorizontal();

                if (sounds.playlistEditorExpanded) {
                    int? playlistToRemove = null;
                    int? playlistToInsertAt = null;
                    int? playlistToMoveUp = null;
                    int? playlistToMoveDown = null;

                    for (var i = 0; i < sounds.musicPlaylists.Count; i++) {
                        EditorGUILayout.Separator();
                        var aList = sounds.musicPlaylists[i];

                        EditorGUI.indentLevel = 1;
                        EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
                        aList.isExpanded = DTGUIHelper.Foldout(aList.isExpanded, "Playlist: " + aList.playlistName);

                        var playlistButtonPressed = DTGUIHelper.AddFoldOutListItemButtons(i, sounds.musicPlaylists.Count, "playlist", false, true);

                        EditorGUILayout.EndHorizontal();

                        if (aList.isExpanded) {
                            EditorGUI.indentLevel = 0;
                            var newPlaylist = EditorGUILayout.TextField("Name", aList.playlistName);
                            if (newPlaylist != aList.playlistName) {
                                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Name");
                                aList.playlistName = newPlaylist;
                            }

                            var crossfadeMode = (MasterAudio.Playlist.CrossfadeTimeMode) EditorGUILayout.EnumPopup("Crossfade Mode", aList.crossfadeMode);
                            if (crossfadeMode != aList.crossfadeMode) {
                                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Crossfade Mode");
                                aList.crossfadeMode = crossfadeMode;
                            }
                            if (aList.crossfadeMode == MasterAudio.Playlist.CrossfadeTimeMode.Override) {
                                var newCF = EditorGUILayout.Slider("Crossfade time (sec)", aList.crossFadeTime, 0f, 10f);
                                if (newCF != aList.crossFadeTime) {
                                    UndoHelper.RecordObjectPropertyForUndo(sounds, "change Crossfade time (sec)");
                                    aList.crossFadeTime = newCF;
                                }
                            }

                            var newFadeIn = EditorGUILayout.Toggle("Fade In First Song", aList.fadeInFirstSong);
                            if (newFadeIn != aList.fadeInFirstSong) {
                                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Fade In First Song");
                                aList.fadeInFirstSong = newFadeIn;
                            }

                            var newFadeOut = EditorGUILayout.Toggle("Fade Out Last Song", aList.fadeOutLastSong);
                            if (newFadeOut != aList.fadeOutLastSong) {
                                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Fade Out Last Song");
                                aList.fadeOutLastSong = newFadeOut;
                            }

                            var newTransType = (MasterAudio.SongFadeInPosition) EditorGUILayout.EnumPopup("Song Transition Type", aList.songTransitionType);
                            if (newTransType != aList.songTransitionType) {
                                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Song Transition Type");
                                aList.songTransitionType = newTransType;
                            }
                            if (aList.songTransitionType == MasterAudio.SongFadeInPosition.SynchronizeClips) {
                                DTGUIHelper.ShowColorWarning("*All clips must be of exactly the same length.");
                            }

                            EditorGUI.indentLevel = 0;
                            var newBulkMode = (MasterAudio.AudioLocation) EditorGUILayout.EnumPopup("Clip Create Mode",  aList.bulkLocationMode);
                            if (newBulkMode != aList.bulkLocationMode) {
                                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Bulk Clip Mode");
                                aList.bulkLocationMode = newBulkMode;
                            }

                            EditorGUILayout.BeginHorizontal();
                            GUILayout.Space(10);
                            GUI.contentColor = Color.green;
                            if (GUILayout.Button(new GUIContent("Equalize Song Volumes"), EditorStyles.toolbarButton)) {
                                EqualizePlaylistVolumes(aList.MusicSettings);
                            }
                            GUILayout.FlexibleSpace();
                            EditorGUILayout.EndHorizontal();
                            GUI.contentColor = Color.white;
                            EditorGUILayout.Separator();

                            EditorGUILayout.BeginVertical();
                            var anEvent = Event.current;

                            GUI.color = Color.yellow;

                            var dragArea = GUILayoutUtility.GetRect(0f,35f,GUILayout.ExpandWidth(true));
                            GUI.Box (dragArea, "Drag Audio clips here to add to playlist!");

                            GUI.color = Color.white;

                            switch (anEvent.type) {
                                case EventType.DragUpdated:
                                case EventType.DragPerform:
                                    if(!dragArea.Contains(anEvent.mousePosition)) {
                                        break;
                                    }

                                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                                    if(anEvent.type == EventType.DragPerform) {
                                        DragAndDrop.AcceptDrag();

                                        foreach (var dragged in DragAndDrop.objectReferences) {
                                            var aClip = dragged as AudioClip;
                                            if(aClip == null) {
                                                continue;
                                            }

                                            AddSongToPlaylist(aList, aClip);
                                        }
                                    }
                                    Event.current.Use();
                                    break;
                            }
                            EditorGUILayout.EndVertical();

                            EditorGUI.indentLevel = 2;

                            int? addIndex = null;
                            int? removeIndex = null;
                            int? moveUpIndex = null;
                            int? moveDownIndex = null;

                            for (var j = 0; j < aList.MusicSettings.Count; j++) {
                                var aSong = aList.MusicSettings[j];
                                var clipName = "Empty";
                                switch (aSong.audLocation) {
                                    case MasterAudio.AudioLocation.Clip:
                                        if (aSong.clip != null) {
                                            clipName = aSong.clip.name;
                                        }
                                        break;
                                    case MasterAudio.AudioLocation.ResourceFile:
                                        if (!string.IsNullOrEmpty(aSong.resourceFileName)) {
                                            clipName = aSong.resourceFileName;
                                        }
                                        break;
                                }
                                EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
                                EditorGUI.indentLevel = 2;

                                if (!string.IsNullOrEmpty(clipName) && string.IsNullOrEmpty(aSong.songName)) {
                                    switch (aSong.audLocation) {
                                        case MasterAudio.AudioLocation.Clip:
                                            aSong.songName = clipName;
                                            break;
                                        case MasterAudio.AudioLocation.ResourceFile:
                                            aSong.songName = clipName;
                                            break;
                                    }
                                }

                                var newSongExpanded = DTGUIHelper.Foldout(aSong.isExpanded, aSong.songName);
                                if (newSongExpanded != aSong.isExpanded) {
                                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Song expand");
                                    aSong.isExpanded = newSongExpanded;
                                }
                                var songButtonPressed = DTGUIHelper.AddFoldOutListItemButtons(j, aList.MusicSettings.Count, "clip", false, true, true);
                                EditorGUILayout.EndHorizontal();

                                if (aSong.isExpanded) {
                                    EditorGUI.indentLevel = 0;

                                    var oldLocation = aSong.audLocation;
                                    var newClipSource = (MasterAudio.AudioLocation) EditorGUILayout.EnumPopup("Audio Origin", aSong.audLocation);
                                    if (newClipSource != aSong.audLocation) {
                                        UndoHelper.RecordObjectPropertyForUndo(sounds, "change Audio Origin");
                                        aSong.audLocation = newClipSource;
                                    }

                                    switch (aSong.audLocation) {
                                        case MasterAudio.AudioLocation.Clip:
                                            var newClip = (AudioClip) EditorGUILayout.ObjectField("Audio Clip", aSong.clip, typeof(AudioClip), true);
                                            if (newClip != aSong.clip) {
                                                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Clip");
                                                aSong.clip = newClip;
                                                aSong.songName = newClip.name;
                                            }
                                            break;
                                        case MasterAudio.AudioLocation.ResourceFile:
                                            if (oldLocation != aSong.audLocation) {
                                                if (aSong.clip != null) {
                                                    Debug.Log("Audio clip removed to prevent unnecessary memory usage on Resource file Playlist clip.");
                                                }
                                                aSong.clip = null;
                                                aSong.songName = string.Empty;
                                            }

                                            EditorGUILayout.BeginVertical();
                                            anEvent = Event.current;

                                            GUI.color = Color.yellow;
                                            dragArea = GUILayoutUtility.GetRect(0f, 20f,GUILayout.ExpandWidth(true));
                                            GUI.Box (dragArea, "Drag Resource Audio clip here to use its name!");
                                            GUI.color = Color.white;

                                            switch (anEvent.type) {
                                                case EventType.DragUpdated:
                                                case EventType.DragPerform:
                                                    if(!dragArea.Contains(anEvent.mousePosition)) {
                                                        break;
                                                    }

                                                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                                                    if(anEvent.type == EventType.DragPerform) {
                                                        DragAndDrop.AcceptDrag();

                                                        foreach (var dragged in DragAndDrop.objectReferences) {
                                                            var aClip = dragged as AudioClip;
                                                            if(aClip == null) {
                                                                continue;
                                                            }

                                                            UndoHelper.RecordObjectPropertyForUndo(sounds, "change Resource Filename");

                                                            var resourceFileName = DTGUIHelper.GetResourcePath(aClip);
                                                            if (string.IsNullOrEmpty(resourceFileName)) {
                                                                resourceFileName = aClip.name;
                                                            }

                                                            aSong.resourceFileName = resourceFileName;
                                                            aSong.songName = aClip.name;
                                                        }
                                                    }
                                                    Event.current.Use();
                                                    break;
                                            }
                                            EditorGUILayout.EndVertical();

                                            var newFilename = EditorGUILayout.TextField("Resource Filename", aSong.resourceFileName);
                                            if (newFilename != aSong.resourceFileName) {
                                                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Resource Filename");
                                                aSong.resourceFileName = newFilename;
                                            }

                                            break;
                                    }

                                    var newVol = EditorGUILayout.Slider("Volume", aSong.volume, 0f, 1f);
                                    if (newVol != aSong.volume) {
                                        UndoHelper.RecordObjectPropertyForUndo(sounds, "change Volume");
                                        aSong.volume = newVol;
                                    }

                                    var newPitch = EditorGUILayout.Slider("Pitch", aSong.pitch, -3f, 3f);
                                    if (newPitch != aSong.pitch) {
                                        UndoHelper.RecordObjectPropertyForUndo(sounds, "change Pitch");
                                        aSong.pitch = newPitch;
                                    }

                                    var newLoop = EditorGUILayout.Toggle("Loop Clip", aSong.isLoop);
                                    if (newLoop != aSong.isLoop) {
                                        UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Loop Clip");
                                        aSong.isLoop = newLoop;
                                    }
                                }

                                switch (songButtonPressed) {
                                    case DTGUIHelper.DTFunctionButtons.Add:
                                        addIndex = j;
                                        break;
                                    case DTGUIHelper.DTFunctionButtons.Remove:
                                        removeIndex = j;
                                        break;
                                    case DTGUIHelper.DTFunctionButtons.ShiftUp:
                                        moveUpIndex = j;
                                        break;
                                    case DTGUIHelper.DTFunctionButtons.ShiftDown:
                                        moveDownIndex = j;
                                        break;
                                    case DTGUIHelper.DTFunctionButtons.Play:
                                        MasterAudio.PreviewerInstance.Stop();
                                        MasterAudio.PreviewerInstance.PlayOneShot(aSong.clip, aSong.volume);
                                        break;
                                    case DTGUIHelper.DTFunctionButtons.Stop:
                                        MasterAudio.PreviewerInstance.clip = null;
                                        MasterAudio.PreviewerInstance.Stop();
                                        break;
                                }
                            }

                            if (addIndex.HasValue) {
                                var mus = new MusicSetting();
                                UndoHelper.RecordObjectPropertyForUndo(sounds, "add song");
                                aList.MusicSettings.Insert(addIndex.Value + 1, mus);
                            } else if (removeIndex.HasValue) {
                                if (aList.MusicSettings.Count <= 1) {
                                    DTGUIHelper.ShowAlert("You cannot delete the last clip. You do not have to use the clips though.");
                                } else {
                                    UndoHelper.RecordObjectPropertyForUndo(sounds, "delete song");
                                    aList.MusicSettings.RemoveAt(removeIndex.Value);
                                }
                            } else if (moveUpIndex.HasValue) {
                                var item = aList.MusicSettings[moveUpIndex.Value];

                                UndoHelper.RecordObjectPropertyForUndo(sounds, "shift up song");

                                aList.MusicSettings.Insert(moveUpIndex.Value - 1, item);
                                aList.MusicSettings.RemoveAt(moveUpIndex.Value + 1);
                            } else if (moveDownIndex.HasValue) {
                                var index = moveDownIndex.Value + 1;
                                var item = aList.MusicSettings[index];

                                UndoHelper.RecordObjectPropertyForUndo(sounds, "shift down song");

                                aList.MusicSettings.Insert(index - 1, item);
                                aList.MusicSettings.RemoveAt(index + 1);
                            }
                        }

                        switch (playlistButtonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            playlistToRemove = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Add:
                            playlistToInsertAt = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.ShiftUp:
                            playlistToMoveUp = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.ShiftDown:
                            playlistToMoveDown = i;
                            break;
                        }
                    }

                    if (playlistToRemove.HasValue) {
                        if (sounds.musicPlaylists.Count <= 1) {
                            DTGUIHelper.ShowAlert("You cannot delete the last Playlist. You do not have to use it though.");
                        } else {
                            UndoHelper.RecordObjectPropertyForUndo(sounds, "delete Playlist");

                            sounds.musicPlaylists.RemoveAt(playlistToRemove.Value);
                        }
                    }
                    if (playlistToInsertAt.HasValue) {
                        var pl = new MasterAudio.Playlist();
                        UndoHelper.RecordObjectPropertyForUndo(sounds, "add Playlist");
                        sounds.musicPlaylists.Insert(playlistToInsertAt.Value + 1, pl);
                    }
                    if (playlistToMoveUp.HasValue) {
                        var item = sounds.musicPlaylists[playlistToMoveUp.Value];
                        UndoHelper.RecordObjectPropertyForUndo(sounds, "shift up Playlist");
                        sounds.musicPlaylists.Insert(playlistToMoveUp.Value - 1, item);
                        sounds.musicPlaylists.RemoveAt(playlistToMoveUp.Value + 1);
                    }
                    if (playlistToMoveDown.HasValue) {
                        var index = playlistToMoveDown.Value + 1;
                        var item = sounds.musicPlaylists[index];

                        UndoHelper.RecordObjectPropertyForUndo(sounds, "shift down Playlist");

                        sounds.musicPlaylists.Insert(index - 1, item);
                        sounds.musicPlaylists.RemoveAt(index + 1);
                    }

                    EditorGUILayout.Separator();
                }
            } else {
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.EndHorizontal();
            }
        }
        // Music playlist End

        // Custom Events Start
        GUI.color = sounds.showCustomEvents ? activeClr : inactiveClr;
        EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
        isExp = EditorGUILayout.Toggle("Show Custom Events", sounds.showCustomEvents);
        if (isExp != sounds.showCustomEvents) {
            UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Show Custom Events");
            sounds.showCustomEvents = isExp;
        }
        EditorGUILayout.EndHorizontal();
        GUI.color = Color.white;

        if (sounds.showCustomEvents) {
            var newEvent = EditorGUILayout.TextField("New Event Name", sounds.newEventName);
            if (newEvent != sounds.newEventName) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "change New Event Name");
                sounds.newEventName = newEvent;
            }

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(154);
            GUI.contentColor = Color.green;
            if (GUILayout.Button("Create New Event", EditorStyles.toolbarButton, GUILayout.Width(100))) {
                CreateCustomEvent(sounds.newEventName);
            }
            GUI.contentColor = Color.white;
            EditorGUILayout.EndHorizontal();

            if (sounds.customEvents.Count == 0) {
                DTGUIHelper.ShowColorWarning("*You currently have no custom events.");
            }

            EditorGUILayout.Separator();

            int? customEventToDelete = null;
            int? eventToRename = null;

            for (var i = 0; i < sounds.customEvents.Count; i++) {
                var anEvent = sounds.customEvents[i];
                EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
                GUILayout.Label(anEvent.EventName, GUILayout.Width(150));

                GUILayout.FlexibleSpace();
                if (Application.isPlaying) {
                    var receivers = MasterAudio.ReceiversForEvent(anEvent.EventName);

                    if (receivers.Count > 0) {
                        GUI.contentColor = Color.green;
                        if (GUILayout.Button("Select", EditorStyles.toolbarButton, GUILayout.Width(50))) {
                            Selection.objects = receivers.ToArray();
                        }
                        GUI.contentColor = Color.white;
                    }

                    GUI.contentColor = Color.yellow;
                    GUILayout.Label(string.Format("Receivers: {0}", receivers.Count));
                    GUI.contentColor = Color.white;
                } else {
                    var newName = GUILayout.TextField(anEvent.ProspectiveName, GUILayout.Width(170));
                    if (newName != anEvent.ProspectiveName) {
                        UndoHelper.RecordObjectPropertyForUndo(sounds, "change Proposed Event Name");
                        anEvent.ProspectiveName = newName;
                    }

                    var buttonPressed = DTGUIHelper.AddCustomEventDeleteIcon(true);

                    switch (buttonPressed) {
                        case DTGUIHelper.DTFunctionButtons.Remove:
                            customEventToDelete = i;
                            break;
                        case DTGUIHelper.DTFunctionButtons.Rename:
                            eventToRename = i;
                            break;
                    }
                }

                EditorGUILayout.EndHorizontal();
            }

            if (customEventToDelete.HasValue) {
                sounds.customEvents.RemoveAt(customEventToDelete.Value);
            }
            if (eventToRename.HasValue) {
                RenameEvent(sounds.customEvents[eventToRename.Value]);
            }
        }

        // Custom Events End

        EditorUtility.SetDirty(target);

        if (sounds.enableFastResponse) {
            this.Repaint();
        }

        //DrawDefaultInspector();
    }
    private static GroupBus GetGroupBus(MasterAudioGroup aGroup) {
        if (_sounds == null) { // this is needed when calling from Group Inspector (mute / solo)
            _sounds = MasterAudio.Instance;
        }

        GroupBus groupBus = null;
        var groupBusIndex = aGroup.busIndex - MasterAudio.HardCodedBusOptions;
        if (groupBusIndex >= 0 && groupBusIndex < _sounds.groupBuses.Count) {
            groupBus = _sounds.groupBuses[groupBusIndex];
        }

        return groupBus;
    }
    private void SoloBus(int busIndex, MasterAudio ma)
    {
        var bus = ma.groupBuses[busIndex];
        bus.isSoloed = !bus.isSoloed;
        if (bus.isSoloed) {
            bus.isMuted = false;
        }

        MasterAudioGroup aGroup = null;
        string sType = string.Empty;

        for (var i = 0; i < this.groups.Count; i++) {
            aGroup = this.groups[i];

            if (aGroup.busIndex != MasterAudio.HARD_CODED_BUS_OPTIONS + busIndex) {
                continue;
            }

            sType = aGroup.name;

            if (Application.isPlaying) {
                if (aGroup.isSoloed) {
                    MasterAudio.UnsoloGroup(sType);
                } else {
                    MasterAudio.SoloGroup(sType);
                }
            }

            aGroup.isSoloed = bus.isSoloed;
            if (bus.isSoloed) {
                aGroup.isMuted = false;
            }
        }
    }
    public override void OnInspectorGUI()
    {
        EditorGUIUtility.LookLikeControls();

        ma = MasterAudio.Instance;
        if (ma != null) {
            GUIHelper.ShowHeaderTexture(ma.logoTexture);
        }

        sounds = (EventSounds)target;

        maInScene = ma != null;
        if (maInScene) {
            groupNames = ma.GroupNames;
            busNames = ma.BusNames;
            playlistNames = ma.PlaylistNames;
        }

        playlistControllerNames = new List<string>();
        playlistControllerNames.Add(MasterAudio.DYNAMIC_GROUP_NAME);
        playlistControllerNames.Add(MasterAudio.NO_GROUP_NAME);

        var pcs = GameObject.FindObjectsOfType(typeof(PlaylistController));
        for (var i = 0; i < pcs.Length; i++) {
            playlistControllerNames.Add(pcs[i].name);
        }

        // populate unused Events for dropdown
        var unusedEventTypes = new List<string>();
        if (!sounds.useStartSound) {
            unusedEventTypes.Add("Start");
        }
        if (!sounds.useEnableSound) {
            unusedEventTypes.Add("Enable");
        }
        if (!sounds.useDisableSound) {
            unusedEventTypes.Add("Disable");
        }
        if (!sounds.useVisibleSound) {
            unusedEventTypes.Add("Visible");
        }
        if (!sounds.useInvisibleSound) {
            unusedEventTypes.Add("Invisible");
        }

        #if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
            // these events don't exist
        #else
            if (!sounds.useCollision2dSound) {
                unusedEventTypes.Add("2D Collision");
            }
            if (!sounds.useTriggerEnter2dSound) {
                unusedEventTypes.Add("2D Trigger Enter");
            }
            if (!sounds.useTriggerExit2dSound) {
                unusedEventTypes.Add("2D Trigger Exit");
            }
        #endif

        if (!sounds.useCollisionSound) {
            unusedEventTypes.Add("Collision");
        }
        if (!sounds.useTriggerEnterSound) {
            unusedEventTypes.Add("Trigger Enter");
        }
        if (!sounds.useTriggerExitSound) {
            unusedEventTypes.Add("Trigger Exit");
        }
        if (!sounds.useParticleCollisionSound) {
            unusedEventTypes.Add("Particle Collision");
        }
        if (!sounds.useMouseEnterSound) {
            unusedEventTypes.Add("Mouse Enter");
        }
        if (!sounds.useMouseClickSound) {
            unusedEventTypes.Add("Mouse Click");
        }
        if (!sounds.useSpawnedSound && sounds.showPoolManager) {
            unusedEventTypes.Add("Spawned");
        }
        if (!sounds.useDespawnedSound && sounds.showPoolManager) {
            unusedEventTypes.Add("Despawned");
        }

        var newDisable = EditorGUILayout.Toggle("Disable Sounds", sounds.disableSounds);
        if (newDisable != sounds.disableSounds) {
            UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Disable Sounds");
            sounds.disableSounds = newDisable;
        }

        if (!sounds.disableSounds) {
            var newSpawnMode = (MasterAudio.SoundSpawnLocationMode) EditorGUILayout.EnumPopup("Sound Spawn Mode", sounds.soundSpawnMode);
            if (newSpawnMode != sounds.soundSpawnMode) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "change Sound Spawn Mode");
                sounds.soundSpawnMode = newSpawnMode;
            }

            var newGiz = EditorGUILayout.Toggle("Show 3D Gizmo", sounds.showGizmo);
            if (newGiz != sounds.showGizmo) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Show 3D Gizmo");
                sounds.showGizmo = newGiz;
            }

            var newPM = EditorGUILayout.Toggle("PoolManager Events", sounds.showPoolManager);
            if (newPM != sounds.showPoolManager) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle PoolManager Events");
                sounds.showPoolManager = newPM;
            }

            var newUnused = EditorGUILayout.Toggle("Minimal Mode", sounds.hideUnused);
            if (newUnused != sounds.hideUnused) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Hide Unused Events");
                sounds.hideUnused = newUnused;
            }

            if (sounds.hideUnused) {
                var newEventIndex = EditorGUILayout.Popup("Event To Activate", -1, unusedEventTypes.ToArray());
                if (newEventIndex > -1) {
                    var selectedEvent = unusedEventTypes[newEventIndex];
                    switch (selectedEvent) {
                        case "Start":
                            sounds.useStartSound = true;
                            break;
                        case "Enable":
                            sounds.useEnableSound = true;
                            break;
                        case "Disable":
                            sounds.useDisableSound = true;
                            break;
                        case "Visible":
                            sounds.useVisibleSound = true;
                            break;
                        case "Invisible":
                            sounds.useInvisibleSound = true;
                            break;
                        case "2D Collision":
                            sounds.useCollision2dSound = true;
                            break;
                        case "2D Trigger Enter":
                            sounds.useTriggerEnter2dSound = true;
                            break;
                        case "2D Trigger Exit":
                            sounds.useTriggerExit2dSound = true;
                            break;
                        case "Collision":
                            sounds.useCollisionSound = true;
                            break;
                        case "Trigger Enter":
                            sounds.useTriggerEnterSound = true;
                            break;
                        case "Trigger Exit":
                            sounds.useTriggerExitSound = true;
                            break;
                        case "Particle Collision":
                            sounds.useParticleCollisionSound = true;
                            break;
                        case "Mouse Enter":
                            sounds.useMouseEnterSound = true;
                            break;
                        case "Mouse Click":
                            sounds.useMouseClickSound = true;
                            break;
                        case "Spawned":
                            sounds.useSpawnedSound = true;
                            break;
                        case "Despawned":
                            sounds.useDespawnedSound = true;
                            break;
                    }
                }
            }
        }

        EditorGUILayout.Separator();
        var suffix = string.Empty;
        if (sounds.disableSounds) {
            suffix = " (DISABLED)";
        } else if (unusedEventTypes.Count > 0 && sounds.hideUnused) {
            suffix = " (" + unusedEventTypes.Count + " hidden)";
        }
        GUILayout.Label("Sound Triggers" + suffix, EditorStyles.boldLabel);

        var disabledText = "";
        if (sounds.disableSounds) {
            disabledText = " (DISABLED) ";
        }

        List<bool> changedList = new List<bool>();

        // trigger sounds
        if (!sounds.hideUnused || sounds.useStartSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);

            var newUseStart = EditorGUILayout.Toggle("Start" + disabledText, sounds.useStartSound);
            if (newUseStart != sounds.useStartSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Start Sound");
                sounds.useStartSound = newUseStart;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useStartSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.startSound, EventSounds.EventType.OnStart));
            }
        }

        if (!sounds.hideUnused || sounds.useEnableSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newUseEnable = EditorGUILayout.Toggle("Enable" + disabledText, sounds.useEnableSound);
            if (newUseEnable != sounds.useEnableSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Enable Sound");
                sounds.useEnableSound = newUseEnable;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useEnableSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.enableSound, EventSounds.EventType.OnEnable));
            }
        }

        if (!sounds.hideUnused || sounds.useDisableSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newDisableSound = EditorGUILayout.Toggle("Disable" + disabledText, sounds.useDisableSound);
            if (newDisableSound != sounds.useDisableSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Disable Sound");
                sounds.useDisableSound = newDisableSound;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useDisableSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.disableSound, EventSounds.EventType.OnDisable));
            }
        }

        if (!sounds.hideUnused || sounds.useVisibleSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newVisible = EditorGUILayout.Toggle("Visible" + disabledText, sounds.useVisibleSound);
            if (newVisible != sounds.useVisibleSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Visible Sound");
                sounds.useVisibleSound = newVisible;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useVisibleSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.visibleSound, EventSounds.EventType.OnVisible));
            }
        }

        if (!sounds.hideUnused || sounds.useInvisibleSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newInvis = EditorGUILayout.Toggle("Invisible" + disabledText, sounds.useInvisibleSound);
            if (newInvis != sounds.useInvisibleSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Invisible Sound");
                sounds.useInvisibleSound = newInvis;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useInvisibleSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.invisibleSound, EventSounds.EventType.OnInvisible));
            }
        }

        #if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
            // these events don't exist
        #else
            if (!sounds.hideUnused || sounds.useCollision2dSound) {
                EditorGUI.indentLevel = 0;
                EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
                var newCollision2d = EditorGUILayout.Toggle("2D Collision" + disabledText, sounds.useCollision2dSound);
                if (newCollision2d != sounds.useCollision2dSound) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle 2D Collision Sound");
                    sounds.useCollision2dSound = newCollision2d;
                }
                EditorGUILayout.EndHorizontal();
                if (sounds.useCollision2dSound && !sounds.disableSounds) {
                    changedList.Add(RenderAudioEvent(sounds.collision2dSound, EventSounds.EventType.OnCollision2D));
                }
            }

            if (!sounds.hideUnused || sounds.useTriggerEnter2dSound) {
                EditorGUI.indentLevel = 0;
                EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
                var newTrigger2d = EditorGUILayout.Toggle("2D Trigger Enter" + disabledText, sounds.useTriggerEnter2dSound);
                if (newTrigger2d != sounds.useTriggerEnter2dSound) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle 2D Trigger Enter Sound");
                    sounds.useTriggerEnter2dSound = newTrigger2d;
                }
                EditorGUILayout.EndHorizontal();
                if (sounds.useTriggerEnter2dSound && !sounds.disableSounds) {
                    changedList.Add(RenderAudioEvent(sounds.triggerEnter2dSound, EventSounds.EventType.OnTriggerEnter2D));
                }
            }

            if (!sounds.hideUnused || sounds.useTriggerExit2dSound) {
                EditorGUI.indentLevel = 0;
                EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
                var newTriggerExit2d = EditorGUILayout.Toggle("2D Trigger Exit" + disabledText, sounds.useTriggerExit2dSound);
                if (newTriggerExit2d != sounds.useTriggerExit2dSound) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle 2D Trigger Exit Sound");
                    sounds.useTriggerExit2dSound = newTriggerExit2d;
                }
                EditorGUILayout.EndHorizontal();
                if (sounds.useTriggerExit2dSound && !sounds.disableSounds) {
                    changedList.Add(RenderAudioEvent(sounds.triggerExit2dSound, EventSounds.EventType.OnTriggerExit2D));
                }
            }
        #endif

        if (!sounds.hideUnused || sounds.useCollisionSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newCollision = EditorGUILayout.Toggle("Collision" + disabledText, sounds.useCollisionSound);
            if (newCollision != sounds.useCollisionSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Collision Sound");
                sounds.useCollisionSound = newCollision;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useCollisionSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.collisionSound, EventSounds.EventType.OnCollision));
            }
        }

        if (!sounds.hideUnused || sounds.useTriggerEnterSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newTrigger = EditorGUILayout.Toggle("Trigger Enter" + disabledText, sounds.useTriggerEnterSound);
            if (newTrigger != sounds.useTriggerEnterSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Trigger Enter Sound");
                sounds.useTriggerEnterSound = newTrigger;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useTriggerEnterSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.triggerSound, EventSounds.EventType.OnTriggerEnter));
            }
        }

        if (!sounds.hideUnused || sounds.useTriggerExitSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newTriggerExit = EditorGUILayout.Toggle("Trigger Exit" + disabledText, sounds.useTriggerExitSound);
            if (newTriggerExit != sounds.useTriggerExitSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Trigger Exit Sound");
                sounds.useTriggerExitSound = newTriggerExit;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useTriggerExitSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.triggerExitSound, EventSounds.EventType.OnTriggerExit));
            }
        }

        if (!sounds.hideUnused || sounds.useParticleCollisionSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newCollision = EditorGUILayout.Toggle("Particle Collision" + disabledText, sounds.useParticleCollisionSound);
            if (newCollision != sounds.useParticleCollisionSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Particle Collision Sound");
                sounds.useParticleCollisionSound = newCollision;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useParticleCollisionSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.particleCollisionSound, EventSounds.EventType.OnParticleCollision));
            }
        }

        if (!sounds.hideUnused || sounds.useMouseEnterSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newMouseEnter = EditorGUILayout.Toggle("Mouse Enter" + disabledText, sounds.useMouseEnterSound);
            if (newMouseEnter != sounds.useMouseEnterSound) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Mouse Enter Sound");
                sounds.useMouseEnterSound = newMouseEnter;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useMouseEnterSound && !sounds.disableSounds) {
                changedList.Add(RenderAudioEvent(sounds.mouseEnterSound, EventSounds.EventType.OnMouseEnter));
            }
        }

        if (!sounds.hideUnused || sounds.useMouseClickSound) {
            EditorGUI.indentLevel = 0;
            EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
            var newMouseClick = EditorGUILayout.Toggle("Mouse Click" + disabledText, sounds.useMouseClickSound);
            if (newMouseClick != sounds.useMouseClickSound) {
                sounds.useMouseClickSound = newMouseClick;
            }
            EditorGUILayout.EndHorizontal();
            if (sounds.useMouseClickSound && !sounds.disableSounds) {
                UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Mouse Click Sound");
                changedList.Add(RenderAudioEvent(sounds.mouseClickSound, EventSounds.EventType.OnMouseClick));
            }
        }

        if (sounds.showPoolManager) {
            if (!sounds.hideUnused || sounds.useSpawnedSound) {
                EditorGUI.indentLevel = 0;
                EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
                var newSpawned = EditorGUILayout.Toggle("Spawned (PoolManager)" + disabledText, sounds.useSpawnedSound);
                if (newSpawned != sounds.useSpawnedSound) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Spawned Sound");
                    sounds.useSpawnedSound = newSpawned;
                }
                EditorGUILayout.EndHorizontal();
                if (sounds.useSpawnedSound && !sounds.disableSounds) {
                    changedList.Add(RenderAudioEvent(sounds.spawnedSound, EventSounds.EventType.OnSpawned));
                }
            }

            if (!sounds.hideUnused || sounds.useDespawnedSound) {
                EditorGUI.indentLevel = 0;
                EditorGUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
                var newDespawned = EditorGUILayout.Toggle("Despawned (PoolManager)" + disabledText, sounds.useDespawnedSound);
                if (newDespawned != sounds.useDespawnedSound) {
                    UndoHelper.RecordObjectPropertyForUndo(sounds, "toggle Despawned Sound");
                    sounds.useDespawnedSound = newDespawned;
                }
                EditorGUILayout.EndHorizontal();
                if (sounds.useDespawnedSound && !sounds.disableSounds) {
                    changedList.Add(RenderAudioEvent(sounds.despawnedSound, EventSounds.EventType.OnDespawned));
                }
            }
        }

        if (GUI.changed || changedList.Contains(true)) {
            EditorUtility.SetDirty(target);
        }

        GUIHelper.RepaintIfUndoOrRedo(this);

        //DrawDefaultInspector();
    }
    // ReSharper disable once FunctionComplexityOverflow
    public override void OnInspectorGUI() {
        EditorGUIUtility.LookLikeControls();

        EditorGUI.indentLevel = 0;
        var isDirty = false;

        _variation = (SoundGroupVariation)target;

        if (MasterAudioInspectorResources.LogoTexture != null) {
            DTGUIHelper.ShowHeaderTexture(MasterAudioInspectorResources.LogoTexture);
        }

        var parentGroup = _variation.ParentGroup;

        if (parentGroup == null) {
            DTGUIHelper.ShowLargeBarAlert("This file cannot be edited in Project View.");
            return;
        }

        EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
        GUI.contentColor = DTGUIHelper.BrightButtonColor;
        if (GUILayout.Button(new GUIContent("Back to Group", "Select Group in Hierarchy"), EditorStyles.toolbarButton, GUILayout.Width(120))) {
            Selection.activeObject = _variation.transform.parent.gameObject;
        }
        GUILayout.FlexibleSpace();
        GUI.contentColor = Color.white;

        _ma = MasterAudio.Instance;
        var maInScene = _ma != null;

        var canPreview = !DTGUIHelper.IsPrefabInProjectView(_variation);

        if (maInScene) {
            _previewer = _ma.gameObject;
            var buttonPressed = DTGUIHelper.DTFunctionButtons.None;
            if (canPreview) {
                buttonPressed = DTGUIHelper.AddVariationButtons();
            }

            switch (buttonPressed) {
                case DTGUIHelper.DTFunctionButtons.Play:
                    if (Application.isPlaying) {
                        MasterAudio.PlaySoundAndForget(_variation.transform.parent.name, 1f, null, 0f, _variation.name);
                    } else {
                        isDirty = true;

                        var calcVolume = _variation.VarAudio.volume * parentGroup.groupMasterVolume;

                        switch (_variation.audLocation) {
                            case MasterAudio.AudioLocation.ResourceFile:
                                StopPreviewer();
                                var fileName = AudioResourceOptimizer.GetLocalizedFileName(_variation.useLocalization, _variation.resourceFileName);
                                GetPreviewer().PlayOneShot(Resources.Load(fileName) as AudioClip, calcVolume);
                                break;
                            case MasterAudio.AudioLocation.Clip:
                                _variation.VarAudio.PlayOneShot(_variation.VarAudio.clip, calcVolume);
                                break;
                            case MasterAudio.AudioLocation.FileOnInternet:
                                if (!string.IsNullOrEmpty(_variation.internetFileUrl)) {
                                    Application.OpenURL(_variation.internetFileUrl);
                                }
                                break;
                        }
                    }
                    break;
                case DTGUIHelper.DTFunctionButtons.Stop:
                    if (Application.isPlaying) {
                        MasterAudio.StopAllOfSound(_variation.transform.parent.name);
                    } else {
                        if (_variation.audLocation == MasterAudio.AudioLocation.ResourceFile) {
                            StopPreviewer();
                        } else {
                            _variation.VarAudio.Stop();
                        }
                    }
                    break;
            }
        }

        EditorGUILayout.EndHorizontal();

        if (maInScene && !Application.isPlaying) {
            DTGUIHelper.ShowColorWarning(MasterAudio.PreviewText);
        }

        var oldLocation = _variation.audLocation;
        if (!Application.isPlaying) {
            var newLocation =
                (MasterAudio.AudioLocation)EditorGUILayout.EnumPopup("Audio Origin", _variation.audLocation);

            if (newLocation != oldLocation) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Audio Origin");
                _variation.audLocation = newLocation;
            }
        } else {
            EditorGUILayout.LabelField("Audio Origin", _variation.audLocation.ToString());
        }

        switch (_variation.audLocation) {
            case MasterAudio.AudioLocation.Clip:
                var newClip = (AudioClip)EditorGUILayout.ObjectField("Audio Clip", _variation.VarAudio.clip, typeof(AudioClip), false);

                if (newClip != _variation.VarAudio.clip) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation.VarAudio, "assign Audio Clip");
                    _variation.VarAudio.clip = newClip;
                }
                break;
            case MasterAudio.AudioLocation.FileOnInternet:
                if (oldLocation != _variation.audLocation) {
                    if (_variation.VarAudio.clip != null) {
                        Debug.Log("Audio clip removed to prevent unnecessary memory usage on File On Internet Variation.");
                    }
                    _variation.VarAudio.clip = null;
                }

                if (!Application.isPlaying) {
                    var newUrl = EditorGUILayout.TextField("Internet File URL", _variation.internetFileUrl);
                    if (newUrl != _variation.internetFileUrl) {
                        AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Internet File URL");
                        _variation.internetFileUrl = newUrl;
                    }
                } else {
                    EditorGUILayout.LabelField("Internet File URL", _variation.internetFileUrl);
                    switch (_variation.internetFileLoadStatus) {
                        case MasterAudio.InternetFileLoadStatus.Loading:
                            DTGUIHelper.ShowLargeBarAlert("Attempting to download.");
                            break;
                        case MasterAudio.InternetFileLoadStatus.Loaded:
                            DTGUIHelper.ShowColorWarning("Downloaded and ready to play.");
                            break;
                        case MasterAudio.InternetFileLoadStatus.Failed:
                            DTGUIHelper.ShowRedError("Failed Download.");
                            break;
                    }
                }

                if (string.IsNullOrEmpty(_variation.internetFileUrl)) {
                    DTGUIHelper.ShowLargeBarAlert("You have not specified a URL for the File On Internet. This Variation will not be available to play without one.");
                }
                break;
            case MasterAudio.AudioLocation.ResourceFile:
                if (oldLocation != _variation.audLocation) {
                    if (_variation.VarAudio.clip != null) {
                        Debug.Log("Audio clip removed to prevent unnecessary memory usage on Resource file Variation.");
                    }
                    _variation.VarAudio.clip = null;
                }

                EditorGUILayout.BeginVertical();
                var anEvent = Event.current;

                GUI.color = DTGUIHelper.DragAreaColor;
                var dragArea = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
                GUI.Box(dragArea, "Drag Resource Audio clip here to use its name!");
                GUI.color = Color.white;

                string newFilename;

                switch (anEvent.type) {
                    case EventType.DragUpdated:
                    case EventType.DragPerform:
                        if (!dragArea.Contains(anEvent.mousePosition)) {
                            break;
                        }

                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                        if (anEvent.type == EventType.DragPerform) {
                            DragAndDrop.AcceptDrag();

                            foreach (var dragged in DragAndDrop.objectReferences) {
                                // ReSharper disable once ExpressionIsAlwaysNull
                                var aClip = dragged as AudioClip;
                                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                                if (aClip == null) {
                                    continue;
                                }

                                // ReSharper disable HeuristicUnreachableCode
                                var useLocalization = false;
                                newFilename = DTGUIHelper.GetResourcePath(aClip, ref useLocalization);
                                if (string.IsNullOrEmpty(newFilename)) {
                                    newFilename = aClip.name;
                                }

                                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Resource filename");
                                _variation.resourceFileName = newFilename;
                                _variation.useLocalization = useLocalization;
                                break;
                                // ReSharper restore HeuristicUnreachableCode
                            }
                        }
                        Event.current.Use();
                        break;
                }
                EditorGUILayout.EndVertical();

                newFilename = EditorGUILayout.TextField("Resource Filename", _variation.resourceFileName);
                if (newFilename != _variation.resourceFileName) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Resource filename");
                    _variation.resourceFileName = newFilename;
                }

                EditorGUI.indentLevel = 1;

                var newLocal = EditorGUILayout.Toggle("Use Localized Folder", _variation.useLocalization);
                if (newLocal != _variation.useLocalization) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Localized Folder");
                    _variation.useLocalization = newLocal;
                }

                break;
        }

        EditorGUI.indentLevel = 0;
        var newVolume = DTGUIHelper.DisplayVolumeField(_variation.VarAudio.volume, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, 0f, true);
        if (newVolume != _variation.VarAudio.volume) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation.VarAudio, "change Volume");
            _variation.VarAudio.volume = newVolume;
        }

        var newPitch = DTGUIHelper.DisplayPitchField(_variation.VarAudio.pitch);
        if (newPitch != _variation.VarAudio.pitch) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation.VarAudio, "change Pitch");
            _variation.VarAudio.pitch = newPitch;
        }

        if (parentGroup.curVariationMode == MasterAudioGroup.VariationMode.LoopedChain) {
            DTGUIHelper.ShowLargeBarAlert("Loop Clip is always OFF for Looped Chain Groups");
        } else {
            var newLoop = EditorGUILayout.Toggle("Loop Clip", _variation.VarAudio.loop);
            if (newLoop != _variation.VarAudio.loop) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation.VarAudio, "toggle Loop");
                _variation.VarAudio.loop = newLoop;
            }
        }

        var newWeight = EditorGUILayout.IntSlider("Voices (Weight)", _variation.weight, 0, 100);
        if (newWeight != _variation.weight) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Voices (Weight)");
            _variation.weight = newWeight;
        }

        var newFxTailTime = EditorGUILayout.Slider("FX Tail Time", _variation.fxTailTime, 0f, 10f);
        if (newFxTailTime != _variation.fxTailTime) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change FX Tail Time");
            _variation.fxTailTime = newFxTailTime;
        }

        var filterList = new List<string>() {
			MasterAudio.NoGroupName,
			"Low Pass",
			"High Pass",
			"Distortion",
			"Chorus",
			"Echo",
			"Reverb"
		};

        var newFilterIndex = EditorGUILayout.Popup("Add Filter Effect", 0, filterList.ToArray());
        switch (newFilterIndex) {
            case 1:
                AddFilterComponent(typeof(AudioLowPassFilter));
                break;
            case 2:
                AddFilterComponent(typeof(AudioHighPassFilter));
                break;
            case 3:
                AddFilterComponent(typeof(AudioDistortionFilter));
                break;
            case 4:
                AddFilterComponent(typeof(AudioChorusFilter));
                break;
            case 5:
                AddFilterComponent(typeof(AudioEchoFilter));
                break;
            case 6:
                AddFilterComponent(typeof(AudioReverbFilter));
                break;
        }

        DTGUIHelper.StartGroupHeader();
        var newUseRndPitch = EditorGUILayout.BeginToggleGroup(" Use Random Pitch", _variation.useRandomPitch);
        if (newUseRndPitch != _variation.useRandomPitch) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Random Pitch");
            _variation.useRandomPitch = newUseRndPitch;
        }

        DTGUIHelper.EndGroupHeader();

        if (_variation.useRandomPitch) {
            var newMode = (SoundGroupVariation.RandomPitchMode)EditorGUILayout.EnumPopup("Pitch Compute Mode", _variation.randomPitchMode);
            if (newMode != _variation.randomPitchMode) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Pitch Compute Mode");
                _variation.randomPitchMode = newMode;
            }

            var newPitchMin = DTGUIHelper.DisplayPitchField(_variation.randomPitchMin, "Random Pitch Min");
            if (newPitchMin != _variation.randomPitchMin) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Random Pitch Min");
                _variation.randomPitchMin = newPitchMin;
                if (_variation.randomPitchMax <= _variation.randomPitchMin) {
                    _variation.randomPitchMax = _variation.randomPitchMin;
                }
            }

            var newPitchMax = DTGUIHelper.DisplayPitchField(_variation.randomPitchMax, "Random Pitch Max");
            if (newPitchMax != _variation.randomPitchMax) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Random Pitch Max");
                _variation.randomPitchMax = newPitchMax;
                if (_variation.randomPitchMin > _variation.randomPitchMax) {
                    _variation.randomPitchMin = _variation.randomPitchMax;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();
        DTGUIHelper.AddSpaceForNonU5(2);

        DTGUIHelper.StartGroupHeader();

        var newUseRndVol = EditorGUILayout.BeginToggleGroup(" Use Random Volume", _variation.useRandomVolume);
        if (newUseRndVol != _variation.useRandomVolume) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Random Volume");
            _variation.useRandomVolume = newUseRndVol;
        }

        DTGUIHelper.EndGroupHeader();

        if (_variation.useRandomVolume) {
            var newMode = (SoundGroupVariation.RandomVolumeMode)EditorGUILayout.EnumPopup("Volume Compute Mode", _variation.randomVolumeMode);
            if (newMode != _variation.randomVolumeMode) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Volume Compute Mode");
                _variation.randomVolumeMode = newMode;
            }

            var volMin = 0f;
            if (_variation.randomVolumeMode == SoundGroupVariation.RandomVolumeMode.AddToClipVolume) {
                volMin = -1f;
            }

            var newVolMin = DTGUIHelper.DisplayVolumeField(_variation.randomVolumeMin, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, volMin, true, "Random Volume Min");
            if (newVolMin != _variation.randomVolumeMin) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Random Volume Min");
                _variation.randomVolumeMin = newVolMin;
                if (_variation.randomVolumeMax <= _variation.randomVolumeMin) {
                    _variation.randomVolumeMax = _variation.randomVolumeMin;
                }
            }

            var newVolMax = DTGUIHelper.DisplayVolumeField(_variation.randomVolumeMax, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, volMin, true, "Random Volume Max");
            if (newVolMax != _variation.randomVolumeMax) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Random Volume Max");
                _variation.randomVolumeMax = newVolMax;
                if (_variation.randomVolumeMin > _variation.randomVolumeMax) {
                    _variation.randomVolumeMin = _variation.randomVolumeMax;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();
        DTGUIHelper.AddSpaceForNonU5(2);

        DTGUIHelper.StartGroupHeader();

        var newSilence = EditorGUILayout.BeginToggleGroup(" Use Random Delay", _variation.useIntroSilence);
        if (newSilence != _variation.useIntroSilence) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Random Delay");
            _variation.useIntroSilence = newSilence;
        }
        DTGUIHelper.EndGroupHeader();

        if (_variation.useIntroSilence) {
            var newSilenceMin = EditorGUILayout.Slider("Delay Min (sec)", _variation.introSilenceMin, 0f, 100f);
            if (newSilenceMin != _variation.introSilenceMin) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Delay Min (sec)");
                _variation.introSilenceMin = newSilenceMin;
                if (_variation.introSilenceMin > _variation.introSilenceMax) {
                    _variation.introSilenceMax = newSilenceMin;
                }
            }

            var newSilenceMax = EditorGUILayout.Slider("Delay Max (sec)", _variation.introSilenceMax, 0f, 100f);
            if (newSilenceMax != _variation.introSilenceMax) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Delay Max (sec)");
                _variation.introSilenceMax = newSilenceMax;
                if (_variation.introSilenceMax < _variation.introSilenceMin) {
                    _variation.introSilenceMin = newSilenceMax;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();
        DTGUIHelper.AddSpaceForNonU5(2);

        DTGUIHelper.StartGroupHeader();

        var newStart = EditorGUILayout.BeginToggleGroup(" Use Random Start Position", _variation.useRandomStartTime);
        if (newStart != _variation.useRandomStartTime) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Random Start Position");
            _variation.useRandomStartTime = newStart;
        }
        DTGUIHelper.EndGroupHeader();

        if (_variation.useRandomStartTime) {
            var newMin = EditorGUILayout.Slider("Start Min (%)", _variation.randomStartMinPercent, 0f, 100f);
            if (newMin != _variation.randomStartMinPercent) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Start Min (%)");
                _variation.randomStartMinPercent = newMin;
                if (_variation.randomStartMaxPercent <= _variation.randomStartMinPercent) {
                    _variation.randomStartMaxPercent = _variation.randomStartMinPercent;
                }
            }

            var newMax = EditorGUILayout.Slider("Start Max (%)", _variation.randomStartMaxPercent, 0f, 100f);
            if (newMax != _variation.randomStartMaxPercent) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Start Max (%)");
                _variation.randomStartMaxPercent = newMax;
                if (_variation.randomStartMinPercent > _variation.randomStartMaxPercent) {
                    _variation.randomStartMinPercent = _variation.randomStartMaxPercent;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();
        DTGUIHelper.AddSpaceForNonU5(2);

        DTGUIHelper.StartGroupHeader();
        var newUseFades = EditorGUILayout.BeginToggleGroup(" Use Custom Fading", _variation.useFades);
        if (newUseFades != _variation.useFades) {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Custom Fading");
            _variation.useFades = newUseFades;
        }
        DTGUIHelper.EndGroupHeader();

        if (_variation.useFades) {
            var newFadeIn = EditorGUILayout.Slider("Fade In Time (sec)", _variation.fadeInTime, 0f, 10f);
            if (newFadeIn != _variation.fadeInTime) {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Fade In Time");
                _variation.fadeInTime = newFadeIn;
            }

            if (_variation.VarAudio.loop) {
                DTGUIHelper.ShowColorWarning("Looped clips cannot have a custom fade out.");
            } else {
                var newFadeOut = EditorGUILayout.Slider("Fade Out time (sec)", _variation.fadeOutTime, 0f, 10f);
                if (newFadeOut != _variation.fadeOutTime) {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Fade Out Time");
                    _variation.fadeOutTime = newFadeOut;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();

        if (GUI.changed || isDirty) {
            EditorUtility.SetDirty(target);
        }

        //DrawDefaultInspector();
    }