using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using TriInspector; namespace R0bbie.Timeline { /// /// Plays one of its sub steps at random /// [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 childSteps = new List(); int lastSelectedStepIndex = -1; /// /// Initialise the StepSwitch /// 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()) { childSteps.Add(t.GetComponent()); } } // Init all child steps foreach (var step in childSteps) { step.Init(attachedStepTimeline, this); } // Reset stored values lastSelectedStepIndex = -1; init = true; } /// /// Initialise the StepSwitch by StepController /// 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()) { childSteps.Add(t.GetComponent()); } } // Init all child steps foreach (var step in childSteps) { step.Init(attachedController, this); } // Reset stored values lastSelectedStepIndex = -1; init = true; } /// /// Play this StepSwitch, in turn playing one randomly selected child step /// 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(); } } } }