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
2
Question by h8crew · Jul 16, 2013 at 01:43 PM · coroutineanother scriptyeild

Waiting for a value to return from another script using coroutines?

Hey guys, I've got 2 C# scripts, script A is trying to get a value from script B using "GetComponent". The problem I'm facing is that that script B is getting that value from a .php script that is accessing a mySQL database and takes a second to get it's value, thus returning a null as the variable I'm trying to access hasn't been set yet. I'm wondering if there is a way for script A to yield for a response from script B without waiting for a set amount of time using "WaitForSeconds".

Comment
Add comment · Show 1
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 gardian06 · Jul 16, 2013 at 08:19 PM 0
Share

why not just

  yield return StartCoroutine();

in scriptA calling the webrequest coroutine in scriptB?

3 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by Bunny83 · Jul 16, 2013 at 08:02 PM

For web requests you could use something like this:

 // C#
 // WebRequest.cs
 public class WebRequest : MonoBehaviour
 {
     private static WebRequest m_Instance = null;
     public static WebRequest Instance
     {
         get
         {
             if (m_Instance == null)
             {
                 m_Instance = (WebRequest)FindObjectOfType(typeof(WebRequest));
                 if (m_Instance == null)
                     m_Instance = (new GameObject("WebRequest")).AddComponent<WebRequest>();
                 DontDestroyOnLoad(m_Instance.gameObject);
             }
             return m_Instance;
         }
     }
     public static Coroutine Get(string aURL, System.Action<bool, string> aCallback)
     {
         return Instance.StartCoroutine(_GetRequest(aURL, aCallback));
     }
     public static Coroutine Post(string aURL, WWWForm aForm, System.Action<bool, string> aCallback)
     {
         return Instance.StartCoroutine(_PostRequest(aURL, aForm, aCallback));
     }
 
     private static IEnumerator _GetRequest(string aURL, System.Action<bool, string> aCallback)
     {
         WWW request = new WWW(aURL);
         yield return request;
         if (string.IsNullOrEmpty(request.error))
         {
             if (aCallback != null)
                 aCallback(true, request.text);
         }
         else
         {
             if (aCallback != null)
                 aCallback(false, request.error);
         }
     }
     private static IEnumerator _PostRequest(string aURL, WWWForm aForm, System.Action<bool, string> aCallback)
     {
         WWW request = new WWW(aURL, aForm);
         yield return request;
         if (string.IsNullOrEmpty(request.error))
         {
             if (aCallback != null)
                 aCallback(true, request.text);
         }
         else
         {
             if (aCallback != null)
                 aCallback(false, request.error);
         }
     }
 }

With this class you can start a webrequest and you can pass a callback to the function which is called when the request has finished. The callback has two parameters, a bool and a string. The bool indicates success and the string is either the response or the error text.

This class can be used from everywhere since it's a singleton. Just do this:

 WebRequest.Get("http://www.google.com", (success, text) =>{
     if (success)
     {
         Debug.Log("Success: " + text);
         // Do something with text
     }
 });

Since the function returns the Coroutine object you can also wait in a coroutine like this:

 IEnumerator Start()
 {
     string result = "";
     yield return WebRequest.Get("http://www.google.com", (success, text) =>result = success?text:"");
     Debug.Log("Done: " + result);
 }

Note: I just rewrote the class here in UA so i didn't test the class, but i use a similar implementation in my projects ;)

Comment
Add comment · Show 5 · 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 bajskorven · Nov 11, 2013 at 09:40 AM 1
Share

It works perfectly for me!!, just one thing... Is there anyway to call "WebRequest.Get" inside a static function? When i do that, i keep getting: "An object reference is required to access non-static member". Well i hope it works, cheers for any answers! :)

avatar image flamy · Nov 11, 2013 at 10:13 AM 1
Share

This is better than my Event system, Thanks @bunny83

avatar image Bunny83 · Nov 11, 2013 at 11:29 AM 0
Share

@bajskorven: Uhm, WebRequest.Get is a static function, so it can be called from anywhere. If you got an error it has to be related with your code. What's the "non static member" the compiler complains about? The WebRequest class actually doesn't have any non static members beside those inherited from $$anonymous$$onoBehaviour.

The only non static member that is used is StartCoroutine and there I use the singleton instance.

If you still have trouble, feel free to post your own question with your actual code. Don't forget to include a link to this question.

avatar image guetta18 · Oct 21, 2018 at 09:28 AM 0
Share

tnx very much! this example is very usefull for me!

just missing returning instance return m_Instance;

avatar image Bunny83 guetta18 · Oct 21, 2018 at 09:30 AM 0
Share

Thanks ^^ you're right. I'll fix it

avatar image
1

Answer by Jamora · Jul 16, 2013 at 07:07 PM

Because of the asynchronous nature of this behavior you're trying to model, I would think it's best to use events. However, Unity has a similar system, without the coding hassle; SendMessage. If you have numerous, or even lots of this kind of behavior, I would suggest using events, as SendMessage is quite costly and could cause lag.

I'm thinking something along these lines for your program logic: as soon as your Script B gets its value, it sends a message to Script A notifying it's ok to read the value.

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
avatar image
0

Answer by scarletshark · Jul 16, 2013 at 06:56 PM

Hmm. I'm wondering if you could use a different method. Maybe you could do

 while (foo == null){
      yield return new WaitForSeconds(0.2f);
 }

The problem with this is that it could loop infinitely if foo remains null. So perhaps instead use a for loop, and after a few loops, return an error.

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

22 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

Related Questions

c# using Lists and IEnumerator's in the same class? 1 Answer

Coroutine not working as expected 1 Answer

Temporary Buff scripts and timers 2 Answers

Yield WaitForSeconds Not Working. Coroutine. 1 Answer

Why does ScreenPointToRay bug when called from IEnumerators? 1 Answer


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