FANDOM


The following is a custom Action that will play music tracks at random. It can be amended to play only within a selected range by changing the Random.Range values.

For details on how to implement custom Actions, see the Manual's "Custom Actions" chapter.

ActionShuffleMusic.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace AC
{

[System.Serializable]
public class ActionShuffleMusic : Action
{

public float fadeTime;
public int fadeTimeParameterID = -1;

public bool loop;
public bool isQueued;

public bool resumeFromStart = true;
public bool resumeIfPlayedBefore = false;


public ActionShuffleMusic ()
{
this.isDisplayed = true;
category = ActionCategory.Sound;
title = "Shuffle music";
description = "Plays or queues random music clips.";
}


override public void AssignValues (List<ActionParameter> parameters)
{
fadeTime = AssignFloat (parameters, fadeTimeParameterID, fadeTime);
}


override public float Run ()
{
if (!isRunning)
{
isRunning = true;
float waitTime = Perform (fadeTime);

if (willWait && waitTime > 0f && !isQueued)
{
return (waitTime);
}
}
else
{
isRunning = false;
}
return 0f;
}


override public void Skip ()
{
Perform (0f);
}


private float Perform (float _time)
{
Music music = KickStarter.stateHandler.GetMusicEngine ();
if (music != null)
{
int trackID = Random.Range (0, KickStarter.settingsManager.musicStorages.Count);
return music.Play (trackID, loop, isQueued, _time, resumeIfPlayedBefore);
}
return 0f;
}


#if UNITY_EDITOR

override public void ShowGUI (List<ActionParameter> parameters)
{
if (AdvGame.GetReferences ().settingsManager != null)
{
SettingsManager settingsManager = AdvGame.GetReferences ().settingsManager;

if (GUILayout.Button ("Music Storage window"))
{
MusicStorageWindow.Init ();
}

if (settingsManager.musicStorages.Count == 0)
{
EditorGUILayout.HelpBox ("Before a track can be selected, it must be added to the Music Storage window.", MessageType.Info);
return;
}

string fadeLabel = "Transition time (s):";
loop = EditorGUILayout.Toggle ("Loop?", loop);
isQueued = EditorGUILayout.Toggle ("Queue?", isQueued);
resumeIfPlayedBefore = EditorGUILayout.Toggle ("Resume if played before?", resumeIfPlayedBefore);

fadeTimeParameterID = Action.ChooseParameterGUI (fadeLabel, parameters, fadeTimeParameterID, ParameterType.Float);
if (fadeTimeParameterID < 0)
{
fadeTime = EditorGUILayout.Slider (fadeLabel, fadeTime, 0f, 10f);
}

if (fadeTime > 0f && !isQueued)
{
willWait = EditorGUILayout.Toggle ("Wait until transition ends?", willWait);
}
}
else
{
EditorGUILayout.HelpBox ("A Settings Manager must be defined for this Action to function correctly. Please go to your Game Window and assign one.", MessageType.Warning);
}

AfterRunningOption ();
}

#endif

}

}