- Home /
Loops without coroutine [SOLVED]
Hii, i need to create a simple loop but without using coroutine we can easily do that outside of unity but as far as i know in unity you must use IEnumerator to do this but that means i need an instance and coroutines does not return values without use of callbacks which i can't use since i need the whole loop not the callback from the start or end
So in unity i did something like in this example but the loop only runs for one frame and then stop which is weird since when you start an loop it should run until reach the ends or freeze the whole machine if there's no end so how can i do a loop without using coroutines?
public void Stuff()
{
float value02 = SimpleLoop();
}
public float SimpleLoop()
{
float value = 0f;
while (value < 10f)
{
value++;
return value;
}
return value;
}
I'm trying to have my own Lerp functions running through a Utility class like plugins as DoTween where you just need to call the function and not implement the whole code behind it that's why i'm trying to do such thing but if there's another way to do it i would appreciate if someone could guide me.
Cheers.
Answer by andrew-lukasik · Aug 09, 2021 at 12:39 AM
But you can callback from the middle of the coroutine, right?(...) coroutines does not return values without use of callbacks which i can't use since i need the whole loop not the callback from the start or end (...)
void Start ()
{
StartCoroutine(
Interpolate( 0 , 1 , 3f , (t) => Debug.Log($"t: {t:G8}") )
);
}
IEnumerator Interpolate ( float src , float dst , float duration , System.Action<float> onValueChanged )
{
float time = 0;
onValueChanged( src );
while( time < duration )
{
yield return null;
time += Time.deltaTime;
float interpolated = Mathf.Lerp( src , dst , time/duration );
onValueChanged( interpolated );
}
}
No. But there is a workaround:do you know if it's possible call coroutines in static classes without instances?
Routine.cs
using System.Collections;
using UnityEngine;
public class Routine : MonoBehaviour
{
static Routine _singleton;
public static void Start ( IEnumerator routine ) => _singleton.StartCoroutine( routine );
public static void Stop ( IEnumerator routine ) => _singleton.StopCoroutine( routine );
public static void Stop ( Coroutine routine ) => _singleton.StopCoroutine( routine );
public static void StopAll () => _singleton.StopAllCoroutines();
[RuntimeInitializeOnLoadMethod( RuntimeInitializeLoadType.BeforeSceneLoad )]
static void OnRuntimeMethodLoad ()
=> GameObject.DontDestroyOnLoad( _singleton = new GameObject($"#{nameof(Routine)}").AddComponent<Routine>() );
}
TickTock.cs (tester)
using System.Collections;
using UnityEngine;
public class TickTock : MonoBehaviour
{
IEnumerator Start ()
{
Routine.Start( Ticks("tick") );
yield return new WaitForSeconds(0.5f);
Routine.Start( Ticks("\ttock") );
yield return new WaitForSeconds(3f);
}
IEnumerator Ticks ( string message )
{
var sec = new WaitForSeconds(1);
while( true )
{
yield return sec;
Debug.Log(message);
}
}
}
Thanks for taking time to answer
I din't knew i could do that din't found anything on microsoft about C# but can i implement this ideia in static classes without instance? Because as far i know coroutines need to be in a instance to work and right now i could not test any asnwer or search about it since i'm out of time but i'll learn about it for sure but do you know if it's possible call coroutines in static classes without instances?
Cheers.
You can only start a coroutine from a MonoBehaviour (which must have an instance), however there's nothing stopping you from using a singleton to create a static MonoBehaviour instance;
public class StaticMonoBehaviour : MonoBehaviour
{
private static StaticMonoBehaviour m_Instance;
public static StaticMonoBehaviour Instance
{
get
{
// Try to find an instance or create one if necessary
if (m_Instance == null)
{
m_Instance = FindObjectOfType<StaticMonoBehaviour>();
if (m_Instance == null)
{
GameObject go = new GameObject ("StaticMonoBehaviour_AutoCreatedInstance");
m_Instance = go.AddComponent<StaticMonoBehaviour>();
}
}
return m_Instance;
}
}
protected void Awake ()
{
// Make sure this is the only instance
if (m_Instance != null)
{
if (m_Instance != this)
{
Destroy (this);
}
return;
}
m_Instance = this;
}
protected void OnDestroy ()
{
if (m_Instance == this)
{
m_Instance = null;
}
}
}
Then, you can just start a coroutine from that instance;
StaticMonoBehaviour.Instance.StartCoroutine (Interpolate (0f, 1f, 5f, (t) =>
{
Debug.Log ("Current time: " + t);
}));
Also, this can be further simplified to just few line:
public class StaticMonoBehaviour : MonoBehaviour
{
public static StaticMonoBehaviour Instance { get; private set; }
[RuntimeInitializeOnLoadMethod( RuntimeInitializeLoadType.BeforeSceneLoad )]
static void OnRuntimeMethodLoad ()
=> GameObject.DontDestroyOnLoad( Instance = new GameObject($"#{nameof(StaticMonoBehaviour)}" ).AddComponent<StaticMonoBehaviour>() );
}
Answer by jihadkhawaja · Aug 08, 2021 at 10:54 PM
public async void Stuff()
{
float value02 = await SimpleLoop();
}
public async Task<float> SimpleLoop()
{
float value = 0f;
while (value < 10f)
value++;
return value;
}
Thanks for the answer i'll search about it, async, task, await never heard about thoose things but found a article exactly about it i'll check it if does what i'm looking for, thanks :).
This doesn't make any sense - you can't await an async function from within a synchronous method, and even if you could it would just end up calling the function on the same thread as the caller (thus blocking it).
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/await
I forgot to add async in the Stuff method, plus if you want to run it on another thread u can simply do float value02 = await Task.Run(async () => { await SimpleLoop(); })
It's good you want to help but I think this code needs some testing and that task a delay. Let's not confuse poor OP more than necessary.
Answer by LordCafe · Aug 10, 2021 at 06:20 PM
Thanks everyone for the help i'm trying all the answer but i'm pretty sure that, now i've enough knowledge to do what i need :).
Cheers.
Your answer
Follow this Question
Related Questions
How to make loop with call to IEnumerator actually pause? 2 Answers
Simplify this code 3 Answers
How would I make my shoot script automatic? 1 Answer
Problem with coroutine 2 Answers
Lerp coroutine not executing 0 Answers