step-timeline/Scripts/StepSwitches/RandomisedStepSwitch.cs

121 lines
3.8 KiB
C#

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TriInspector;
namespace R0bbie.Timeline
{
/// <summary>
/// Plays one of its sub steps at random
/// </summary>
[AddComponentMenu("Timeline/StepSwitches/Randomised (Step Switch)")]
public class RandomisedStepSwitch : StepSwitch
{
// Add ability to avoid repeating the same option twice
[SerializeField, Tooltip("Try to avoid playing the same step twice in a row (only applicable if a StepLooper is repeating this switch!)")]
bool avoidRepeats;
List<Step> childSteps = new List<Step>();
int lastSelectedStepIndex = -1;
/// <summary>
/// Initialise the StepSwitch
/// </summary>
public override void Init(StepTimeline _stepTimeline)
{
// Setup necessary refs such as parent timeline
attachedStepTimeline = _stepTimeline;
// Get refs to all child steps (only 1 level deep)
foreach (Transform t in transform)
{
if (t.GetComponent<Step>())
{
childSteps.Add(t.GetComponent<Step>());
}
}
// Init all child steps
foreach (var step in childSteps)
{
step.Init(attachedStepTimeline, this);
}
// Reset stored values
lastSelectedStepIndex = -1;
init = true;
}
/// <summary>
/// Initialise the StepSwitch by StepController
/// </summary>
public override void Init(StepController _controller)
{
// Setup necessary refs such as parent controller
attachedController = _controller;
// Get refs to all child steps (only 1 level deep)
foreach (Transform t in transform)
{
if (t.GetComponent<Step>())
{
childSteps.Add(t.GetComponent<Step>());
}
}
// Init all child steps
foreach (var step in childSteps)
{
step.Init(attachedController, this);
}
// Reset stored values
lastSelectedStepIndex = -1;
init = true;
}
/// <summary>
/// Play this StepSwitch, in turn playing one randomly selected child step
/// </summary>
public override void Play()
{
isActive = true;
// If no child step options exist, do nothing, and just skip onto the next step in the timeline
if (childSteps.Count < 1)
Continue();
// Select a child step at random
int randomStepIndex = Random.Range(0, (childSteps.Count - 1));
// If selected step is same as last one, try selecting avoid
if (avoidRepeats && randomStepIndex == lastSelectedStepIndex)
randomStepIndex = Random.Range(0, (childSteps.Count - 1));
// Set the active step option to the one selected
activeStepOption = childSteps[randomStepIndex];
// Play the selected option, unless it's null (in which case just play next step in timeline)
if (activeStepOption)
{
activeMode = Mode.PlayingChildStep;
activeStepOption.Play();
}
else
{
Debug.Log("The option selected by the step switch was null, so just proceeding to next step in timeline.");
Continue();
}
}
}
}