step-timeline/Scripts/Steps/StepLooper.cs

125 lines
3.7 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
using UnityEngine;
using TriInspector;
namespace R0bbie.Timeline
{
/// <summary>
/// Simple step type which loops back to a previous step, until a set condition is met
/// </summary>
public class StepLooper : Step
{
[Title("Loop Setup")]
[SerializeField] Step loopBackToStep;
enum LoopCondition
{
NumberLoops,
IfStepPlayed,
IfCommandCompleted,
IfTriggerTriggered
}
[SerializeField] LoopCondition loopUntil;
[ShowIf(nameof(loopUntil), LoopCondition.NumberLoops)]
[SerializeField] int loopForIterations;
[ShowIf(nameof(loopUntil), LoopCondition.IfStepPlayed)]
[SerializeField] Step stepToCheck;
[ShowIf(nameof(loopUntil), LoopCondition.IfCommandCompleted)]
[SerializeField] StepCmd commandToCheck;
[ShowIf(nameof(loopUntil), LoopCondition.IfTriggerTriggered)]
[SerializeField] TimelineTrigger triggerToCheck;
int loopCounter = 0;
/// <summary>
/// Play this step, which here means triggering the loop back to a previous step
/// </summary>
public override void Play()
{
Debug.Log(name + " - Started");
isActive = true;
Continue();
}
/// <summary>
/// Continue (either looping back to a previous step, or playing ahead to next in timeline if loop has been broken)
/// </summary>
public override void Continue()
{
bool breakConditionReached = false;
// Increase loop counter
loopCounter++;
// First check if this loop has reached its break condition
switch (loopUntil)
{
case LoopCondition.NumberLoops:
if (loopCounter >= loopForIterations)
breakConditionReached = true;
break;
case LoopCondition.IfStepPlayed:
if (stepToCheck.wasCompleted)
breakConditionReached = true;
break;
case LoopCondition.IfCommandCompleted:
if (commandToCheck.completed)
breakConditionReached = true;
break;
case LoopCondition.IfTriggerTriggered:
if (triggerToCheck.triggered)
breakConditionReached = true;
break;
}
if (breakConditionReached)
{
Debug.Log(name + " - Completed");
// Play the next step after this looper in the timeline
if (parentStepGroup != null)
parentStepGroup.Continue();
else
attachedStepTimeline.PlayNextStep();
isActive = false;
wasCompleted = true;
return;
}
// Otherwise, loop again!
// Play the step we're looping back to
if (attachedStepTimeline != null)
attachedStepTimeline.GoToStepAndPlay(loopBackToStep);
else
Debug.LogError("Tried to play a StepLooper with a StepController, which isn't currently compatible. Must be a child of a Timeline to function.");
isActive = false;
}
}
}