How loop over the targets in the coroutine over again nonstop ?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FIMSpace.FLook;
using System.Linq;

public class MultipleLookAtTargets : MonoBehaviour
{
    public FLookAnimator lookAnimator;
    public List<Transform> targets = new List<Transform>();
    public float switchingTime;
    public bool switchingLoop = false;

    // Start is called before the first frame update
    private void Start()
    {
        lookAnimator.MaximumDistance = 10f;

        var targetsTags = GameObject.FindGameObjectsWithTag("Target").ToList();
        if (targetsTags != null && targets.Count == 0)
        {
            for (int i = 0; i < targetsTags.Count; i++)
            {
                targets.Add(targetsTags[i].transform);
            }
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.V))
        {
            StartCoroutine(SwitchTargetsPeriodically());
        }
    }

    IEnumerator SwitchTargetsPeriodically()
    {
        for (int i = 0; i < targets.Count; i++)
        {
            lookAnimator.ObjectToFollow = targets[i];

            yield return new WaitForSeconds(switchingTime);
        }
    }
}

How to use the switchingLoop if it’s true to loop over the targets in the coroutine ?
Now it’s iterating over the targets only once but I want that if the flag is true iterate over and over again the targets.

Wrap your for loop in your couroutine inside a do while

do
{
//your code
}
while(switchingLoop);
1 Like

Each frame, check if the bool is true, then do the loop:

public class Example : MonoBehaviour
{
    bool isLooping = false;

    void Update()
    {
        if (isLooping) DoLoop();
    }

    void DoLoop()
    {
        // Loop here
    }
}
1 Like

It’s working but if I interrupt the loop in the middle and change the flag switchingLoop to false it will stop at the last target but than if I set the flag switchingLoop back to true again it will not loop nonstop again why is that ?

IEnumerator SwitchTargetsPeriodically()
    {
        do
        {
            for (int i = 0; i < targets.Count; i++)
            {
                lookAnimator.ObjectToFollow = targets[i];

                yield return new WaitForSeconds(switchingTime);
            }
        }
        while (switchingLoop);
    }

When it’s the flag is true and it’s iterating if in the middle I change the flag to false it will stop but if I change back to true it will not continue the do/while I will need to start the game over again with the flag set to true.

That’s because the coroutine ends after the bool is set to false and the loop finishes.

1 Like