Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by LordCafe · Aug 08, 2021 at 10:45 PM · scripting problemcoroutineloops

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.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by andrew-lukasik · Aug 09, 2021 at 12:39 AM

(...) 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 (...)

But you can callback from the middle of the coroutine, right?
 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 );
     }
 }

do you know if it's possible call coroutines in static classes without instances?

No. But there is a workaround:

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);
         }
     }
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image LordCafe · Aug 09, 2021 at 04:49 PM 0
Share

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.

avatar image Namey5 LordCafe · Aug 09, 2021 at 10:18 PM 2
Share

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);
 }));
avatar image andrew-lukasik Namey5 · Aug 10, 2021 at 11:54 AM 1
Share

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>() );
 }
avatar image
1

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;
      }
Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image LordCafe · Aug 09, 2021 at 12:00 AM 1
Share

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 :).

avatar image Namey5 · Aug 09, 2021 at 12:47 AM 1
Share

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

avatar image jihadkhawaja Namey5 · Aug 09, 2021 at 01:05 AM 0
Share

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(); })

avatar image andrew-lukasik jihadkhawaja · Aug 09, 2021 at 01:27 AM 1
Share

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.

avatar image
0

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

229 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges